问题描述:

I followed a tutorial to be able to create an activity with two buttons which should then open two fragments (so the fragment first opened is replaced by the second one opened) - However my app crashes.

My code is

public class Play extends 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);

}

And the fragments are basically identical (with names changed etc)

public class FragmentOne extends 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;

}

}

The XML file for Play has a bunch of imagebuttons and then the fragment as:

<fragment

android:layout_width="wrap_content"

android:layout_height="188dp"

android:id="@+id/output" />

How come it crashes?

相关阅读:
Top