所以我写了这个简单的标签导航。它有两个选项卡,称为“片段 1”和“片段 2”。如果您点击其中任何一个,它应该在内容区域显示相应的文本“Fragment 1”或“Fragment 2”。我的代码在开始时运行良好。
但是,当我将设备转为横向时,文本会混乱。它在同一位置显示带有 1 和 2 组合的 Fragment。我认为这两个文本同时显示。发生此错误后,我尝试更改选项卡的文本保持不变。当我从横向更改为纵向时,也会发生这种情况。这是什么原因造成的?
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;
}
}
片段1.java
public class Fragment1 extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.frag1, container, false);
}
}
片段2.java
public class Fragment2 extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.frag2, container, false);
}
}