更改方向时,操作栏选项卡中的错误

时间:2013-11-02 05:41:37

标签: java android android-fragments tabs

所以我写了这个简单的标签导航。它有两个标签叫做“Fragment 1”和“Fragment 2”。如果您点击其中任何一个,它应在内容区域中显示相应的文本“片段1”或“片段2”。我的代码在开始时工作正常。

但是,当我将设备转换为横向时,文本会混乱。它在同一位置显示片段与1和2的组合。我认为这两个文本同时显示。文本仍然是这样我尝试在发生此错误后更改选项卡。当我从横向更改为纵向时,也会发生这种情况。造成这种情况的原因是什么?

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActionBar ab = getActionBar();
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    Tab tab = ab.newTab().setText(R.string.frag1).setTabListener(new MyTabListener(this, Fragment1.class.getName()));
    ab.addTab(tab);

    tab = ab.newTab().setText(R.string.frag2).setTabListener(new MyTabListener(this, Fragment2.class.getName()));
    ab.addTab(tab);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private class MyTabListener implements ActionBar.TabListener
{
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mFragName;

    public MyTabListener(Activity activity, String fragName) {
        mActivity = activity;
        mFragName = fragName;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        mFragment = Fragment.instantiate(mActivity, mFragName);
        ft.add(android.R.id.content, mFragment);

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(mFragment);
        mFragment = null;

    }

}

Fragment1.java

public class Fragment1 extends Fragment
{   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
    {
        return inflater.inflate(R.layout.frag1, container, false);
    }
}

Fragment2.java

public class Fragment2 extends Fragment
{   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
    {
        return inflater.inflate(R.layout.frag2, container, false);
    }
}

1 个答案:

答案 0 :(得分:2)

你需要在onTabSelected()方法中使用replace()而不是add()方法。