Fragment在android中常用也非常用的 就不做过多的介绍了
MainActivity界面
public class MainActivity extends FragmentActivity {
private FragmentManager manager;
private Frag01 frag01;
private Frag02 frag02;
private Frag03 frag03;
private FrameLayout frag;
private RadioGroup radio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radio = findViewById(R.id.radio);
frag = findViewById(R.id.frag);
//新建事务
manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
frag01 = new Frag01();
frag02 = new Frag02();
frag03 = new Frag03();
//添加事务
transaction.add(R.id.frag,frag01);
transaction.add(R.id.frag,frag02);
transaction.add(R.id.frag,frag03);
transaction.show(frag01).hide(frag02).hide(frag03);
transaction.commit();
//实现点击切换
radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
private FragmentTransaction transaction1;
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//开启新事务
transaction1 = manager.beginTransaction();
switch (checkedId){
case R.id.but1:
transaction1.show(frag01).hide(frag02).hide(frag03);
break;
case R.id.but2:
transaction1.show(frag02).hide(frag01).hide(frag03);
break;
case R.id.but3:
transaction1.show(frag03).hide(frag02).hide(frag01);
break;
}
transaction1.commit();
}
});
}
}
布局页面
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">
<FrameLayout
android:id="@+id/frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</FrameLayout>
<RadioGroup
android:id="@+id/radio"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/but1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:button="@null"
android:drawableTop="@drawable/sel_but"
android:text="首页"/>
<RadioButton
android:id="@+id/but2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:button="@null"
android:layout_weight="1"
android:drawableTop="@drawable/sel_but"
android:text="社区"/>
<RadioButton
android:id="@+id/but3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:button="@null"
android:layout_weight="1"
android:drawableTop="@drawable/sel_but"
android:text="我的"/>
</RadioGroup>
</LinearLayout>