You're creating a new instance of MainFragment
rather than using the one defined in your activity_main2
layout.
But even if you referenced it correctly, you would still throw an IllegalStateException
because you can't add arguments to a Fragment
that's defined in your xml. Use a FrameLayout
instead and call FragmentTransaction.replace
.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
final Bundle args = new Bundle();
args.putInt("number", 3);
final MainFragment mf = new MainFragment();
mf.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.fragment, mf).commit();