Skip to content Skip to sidebar Skip to footer

Change A Fragment

I have a few fragment which need to show after check RadioButton. How to realize add/replace fragment if I didn't know which fragment was previosly? And How to do default show frag

Solution 1:

If I understood you correctly,

MainActivity:

publicclassMainActivityextendsFragmentActivity {

FragmentTransaction ft;
Fragment1           frg1;
Fragment2           frg2;

publicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    frg1 = newFragment1();
    frg2 = newFragment2();

    RadioButtonbtn1= (RadioButton) findViewById(R.id.radio1);
    btn1.setChecked(true);
    getSupportFragmentManager().beginTransaction().add(R.id.frame, frg1).commit();

    // set listener
    ((RadioGroup) findViewById(R.id.radio_group)).setOnCheckedChangeListener(newOnCheckedChangeListener() {
        @OverridepublicvoidonCheckedChanged(RadioGroup group, int checkedId) {
            ft = getSupportFragmentManager().beginTransaction();
            switch (checkedId) {
                case R.id.radio1:
                    ft.replace(R.id.frame, frg1);
                    break;
                case R.id.radio2:
                    ft.replace(R.id.frame, frg2);
                    break;
            }
            ft.commit();
        }
    });
}
}

Fragment1:

publicclassFragment1extendsFragment {

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    container.removeAllViews();
    return inflater.inflate(R.layout.fragment1, null);
}
}

Fragment2:

publicclassFragment2extendsFragment {

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    container.removeAllViews();
    return inflater.inflate(R.layout.fragment2, null);
}
}

activity_main:

<RadioGroupandroid:id="@+id/radio_group"android:layout_width="wrap_content"android:layout_height="wrap_content" ><RadioButtonandroid:id="@+id/radio1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="fragment1" /><RadioButtonandroid:id="@+id/radio2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="fragment2" /></RadioGroup><FrameLayoutandroid:id="@+id/frame"android:layout_width="match_parent"android:layout_height="match_parent" ></FrameLayout>

fragment1.xml:

<TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:text="Fragment1" ></TextView>

fragment2.xml:

<TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:text="Fragment2" ></TextView>

Post a Comment for "Change A Fragment"