我按照教程创建了一个带有两个按钮的活动,然后打开两个片段(所以首先打开的片段被第二个打开的片段替换) - 但是我的应用程序崩溃了。 我的代码是
公共课Play扩展了MainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
Fragment fragment1;
if(v == findViewById(R.id.imageButton10)) {
fragment1 = new FragmentOne();
} else {
fragment1 = new FragmentTwo();
}
fragTrans.replace(R.id.output, fragment1);
fragTrans.commit();
}
};
ImageButton imageBtn10 = (ImageButton)findViewById(R.id.imageButton10);
imageBtn10.setOnClickListener(listener);
ImageButton imageBtn9 = (ImageButton)findViewById(R.id.imageButton9);
imageBtn9.setOnClickListener(listener);
}
片段基本相同(名称改变等)
公共类FragmentOne扩展了Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_fragment_one, container, false);
TextView output = (TextView) getView().findViewById(R.id.textView4);
output.setText("Fragment One");
return v;
}
}
Play的XML文件有一堆图像按钮,然后片段为:
<fragment
android:layout_width="wrap_content"
android:layout_height="188dp"
android:id="@+id/output" />
怎么会崩溃?