我想创建一个Activity
显示用户可以通过的菜单。通过单击一个项目,将显示一个新屏幕,允许用户进行更多选项(类似向导)。
我想用Fragment
s 来实现这个,但它对我不起作用。
现在我有:
main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/main_fragmentcontainer" >
<fragment
android:id="@+id/mainmenufragment"
android:name="com.myapp.MainMenuFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<fragment
android:id="@+id/secondmenufragment"
android:name="com.myapp.SecondMenuFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
MainMenuFragment
有一个OnClickListener
:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mainmenu, container, false);
setupButton(view);
return view;
}
/* Button setup code omitted */
@Override
public void onClick(View v) {
SherlockFragment secondRunMenuFragment = (SherlockFragment) getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.secondmenufragment);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, secondMenuFragment); //also crashes with R.id.main_fragmentcontainer
transaction.addToBackStack(null);
transaction.commit();
}
现在,当我按下按钮时,应用程序会因为这个 logcat 而崩溃:
06-27 01:45:26.309: E/AndroidRuntime(8747): java.lang.IllegalStateException: 无法更改片段 SecondMenuFragment{405e2a70 #1 id=0x7f060029} 的容器 ID:现在是 2131099689 2131099687
06-27 01:45 :26.309: E/AndroidRuntime(8747): at android.support.v4.app.BackStackRecord.doAddOp(Unknown Source)
06-27 01:45:26.309: E/AndroidRuntime(8747): at android.support.v4.app .BackStackRecord.replace(未知来源)
06-27 01:45:26.309: E/AndroidRuntime(8747): at android.support.v4.app.BackStackRecord.replace(未知来源)
06-27 01:45:26.309: E /AndroidRuntime(8747):在 com.myapp.MainMenuFragment$MyButtonOnClickListener.onClick(MainMenuFragment.java:52)
我究竟做错了什么?