1

我有一些片段需要在检查 RadioButton 后显示。如果我不知道之前是哪个片段,如何实现添加/替换片段?以及如何做默认显示片段?

4

1 回答 1

5

如果我理解正确的话,

主要活动:

public class MainActivity extends FragmentActivity {

FragmentTransaction ft;
Fragment1           frg1;
Fragment2           frg2;

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

    frg1 = new Fragment1();
    frg2 = new Fragment2();

    RadioButton btn1 = (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(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(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();
        }
    });
}
}

片段1:

public class Fragment1 extends Fragment {

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

片段2:

public class Fragment2 extends Fragment {

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

活动主:

<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment1" />

    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fragment2" />
</RadioGroup>

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</FrameLayout>

片段1.xml:

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

片段2.xml:

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

于 2013-08-27T10:39:06.447 回答