[英]Problem with the action bar and fragments: the app crashes when go back on a tab
我是Android的新手,我嘗試在Android Honeycomb 3.0上創建應用程序。這是我的問題:我的操作欄中有2個選項卡。 選項卡1使用片段A和B,選項卡2使用片段C和D。加載應用程序時,選擇了選項卡1,並顯示片段A和B。 然后,我單擊選項卡2,它也可以正常工作。 但是,當我返回到選項卡1時,應用程序崩潰並顯示以下錯誤:
android.view.InflateException:二進制XML文件第6行:錯誤誇大了類片段..... .....造成原因:java.lang.IllegalArgumentException:二進制XML文件第6行:重復ID 0x7f .... .........標記為null或父ID為0x .......
這是我的代碼:
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
ActionBar.Tab tab1 = bar.newTab().setText("tab 1");
ActionBar.Tab tab2 = bar.newTab().setText("tab 2");
Fragment frag1 = new FragmentOne();
Fragment frag2 = new FragmentTwo();
tab1.setTabListener(new MyTabListener(frag1));
tab2.setTabListener(new MyTabListener(frag2));
bar.addTab(tab1);
bar.addTab(tab2);
}
private class MyTabListener implements ActionBar.TabListener {
private Fragment mFragment;
// Called to create an instance of the listener when adding a new tab
public MyTabListener(Fragment fragment) {
mFragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragments, mFragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(mFragment);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
}
片段1:
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View mainView = inflater.inflate(R.layout.fragments, container, false);
return mainView;
}
}
Fragments.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="ch.comem.test.FragmentOneA"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/idFragment_one_a"
android:layout_weight="30">
</fragment>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="ch.comem.test.FragmentOneB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/idFragment_one_b"
android:layout_weight="70">
</fragment>
謝謝你的幫助。
我看到的主要問題是您的FragmentOne
類會增加fragments.xml
,它本身包含對另外兩個片段FragmentOne
和FragmentTwo
引用。 這是無效的,因為片段不能包含其他片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.