替换FragmentTabHost中的片段

时间:2013-10-22 05:26:34

标签: android android-fragments

我在Fragments中实施了少量FragmentTabHost,使用:

FragmentActivity类内:

FragmentTabHost mTabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.e(TAG, "onCreateView()");

    setContentView(R.layout.activity_main);

    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("audio").setIndicator("Audio"),
            AudioFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("video").setIndicator("Video"),
            VideoFragment.class, null);

    mTabHost.setOnTabChangedListener(this);
}

其中一个fragmentAudioFragment有一个button,它应该在AudioFragment的当前片段上打开一个新片段。

Inside AudioFragment.class

@Override
public void onClick(View button) {
    switch (button.getId()) {
    case R.id.bOpenNewFragment:

        // WHAT TO CODE, TO REPLACE THE CURRENT FRAGMENT OF AudioFragment 

        break;
    }

}

尝试使用以下代码

Fragment fragment = new ShowAudioDetailsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.realtabcontent, fragment);
transaction.addToBackStack(null);
transaction.commit();

但是,当我切换到另一个标签时出现了问题(状态未得到维护,而新片段的视图与其他标签的布局合并)。

那么如何用FragmentTabHost中打开的片段替换片段

谢谢

1 个答案:

答案 0 :(得分:0)

只需添加此行

即可
((RelativeLayout) findViewById(R.id.realtabcontent)).removeAllViews(); // whatever layout you have

之前:

transaction.replace(R.id.realtabcontent, fragment);