这是一个Fragment页面碎片
public class Fra1 extends Fragment {
@Nullable
@Override
//每个Fragment页面简单操作
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView te=new TextView(getActivity());
te.setText("首页");
return te;
}
}
这是在MainActivity里的操作 如下面代码:
public class Main2Activity extends AppCompatActivity {
private FrameLayout mFa;
private RadioButton mRa1;
private RadioButton mRa2;
private RadioButton mRa3;
private RadioButton mRa4;
private RadioButton mRa5;
private RadioGroup mRa;
private Fra1 f1;
private Fra2 f2;
private Fra3 f3;
private Fra4 f4;
private Fra5 f5;
//集合用来添加每个Fragment
List<Fragment> li=new ArrayList<>();
private FragmentManager supportFragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//获取RadioGroup
mRa = (RadioGroup) findViewById(R.id.ra);
shuju();//这是下面每个Fragment碎片页面
supportFragmentManager = getSupportFragmentManager();//获取支持操控碎片的管理
FragmentTransaction fr = supportFragmentManager.beginTransaction();//开始事务
fr.add(R.id.fa,li.get(0)).commit();//先把Fragment添加到事务里
mRa.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i){
case R.id.ra1://这是每个RadioButton按钮 然后进行替换添加
supportFragmentManager.beginTransaction().replace(R.id.fa,li.get(0)).commit();
break;
case R.id.ra2:
supportFragmentManager.beginTransaction().replace(R.id.fa,li.get(1)).commit();
break;
case R.id.ra3:
supportFragmentManager.beginTransaction().replace(R.id.fa,li.get(2)).commit();
break;
case R.id.ra4:
supportFragmentManager.beginTransaction().replace(R.id.fa,li.get(3)).commit();
break;
case R.id.ra5:
supportFragmentManager.beginTransaction().replace(R.id.fa,li.get(4)).commit();
break;
}
}
});
}
public void shuju(){
f1 = new Fra1();
f2 = new Fra2();
f3 = new Fra3();
f4 = new Fra4();
f5 = new Fra5();
li.add(f1);
li.add(f2);
li.add(f3);
li.add(f4);
li.add(f5);
}
}