Android 1.6 & Fragment & Tabhost

一曲冷凌霜 提交于 2019-11-30 01:57:02

The problem is that your MyActivity tries to reach out to the enclosing MainActivity by using android.R.id.tabcontent as a container id. This is not possible. Instead, MyActivity needs to have its own layout (e.g. a FrameLayout) which can be used as the parent for the Fragment. In this layout, there must exist a view that can be referenced by id.

Let's say you have a layout called activity_layout.xml which contains a FrameLayout with the id 'framelayout'. You can then modify the onCreate method in MyActivity to something like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View parent = getLayoutInflater().inflate(R.layout.activity_layout, null);
    setContentView(parent);

    fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment fragment = MyFragment.newInstance();
    fragmentTransaction.add(R.id.framelayout, fragment, "MyFragment");
    fragmentTransaction.commit();
}

In other words, MyActivity needs to be able to work on its own. Try to make it work first, and then embed MyActivity in the MainActivity containing the TabHost.

Why don't you create your own tabbar. It's verry easy to build. Just add a LinearLayout with some buttons in it and set the onClickListener to switch fragments by using the FragmentManager. The Fragment manager can be obtained from a FragmentActivity.

FragmentManager fragmentManager = getSupportFragmentManager();

In the onClick handler you just do a transaction to the switch to the correct fragments.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!