Fragment与RadioGroup简单运用

来源:互联网 发布:装饰装修设计软件 编辑:程序博客网 时间:2024/06/09 19:29
//主页面布局
<FrameLayout    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="9"    android:id="@+id/frag"></FrameLayout><RadioGroup    android:id="@+id/rg"    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="1"    android:orientation="horizontal">    <RadioButton        android:id="@+id/btn1"        android:layout_width="0dp"        android:layout_weight="1"        android:button="@null"        android:text="首页"        android:gravity="center"        android:layout_height="match_parent" />    <RadioButton        android:id="@+id/btn2"        android:layout_width="0dp"        android:layout_weight="1"        android:button="@null"        android:text="发现"        android:gravity="center"        android:layout_height="match_parent" />    <RadioButton        android:id="@+id/btn3"        android:layout_width="0dp"        android:text="下载"        android:gravity="center"        android:layout_height="match_parent"        android:layout_weight="1"        android:button="@null" />    <RadioButton        android:id="@+id/btn4"        android:layout_width="0dp"        android:layout_weight="1"        android:text="我的"        android:gravity="center"        android:button="@null"        android:layout_height="match_parent" /></RadioGroup>
//MainActivity类
public class MainActivity extends AppCompatActivity {    private RadioGroup rg;    private FrameLayout frag;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);
//找到控件        rg = (RadioGroup) findViewById(R.id.rg);        frag = (FrameLayout) findViewById(R.id.frag);
        addFragment(new Fragment01());
//RadioGroup的点击事件        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {                switch (checkedId){                    case R.id.btn1:                        addFragment(new Fragment01());                        break;                    case R.id.btn2:                        addFragment(new Fragment02());                        break;                    case R.id.btn3:                        addFragment(new Fragment03());                        break;                    case R.id.btn4:                        addFragment(new Fragment04());                        break;                }            }        });    }    public void addFragment(Fragment f){        FragmentManager manager=getSupportFragmentManager();        FragmentTransaction fragmentTransaction = manager.beginTransaction();        fragmentTransaction.replace(R.id.frag,f);        fragmentTransaction.commit();    }}