//初始化控件
- private void initView() {
- rb_1 = (RadioButton) findViewById(R.id.rb_01);
- rb_2 = (RadioButton) findViewById(R.id.rb_02);
- rb_3 = (RadioButton) findViewById(R.id.rb_03);
- rb_4 = (RadioButton) findViewById(R.id.rb_04);
- private void initEvents() {
- rb_1.setOnClickListener(this);
- rb_2.setOnClickListener(this);
- rb_3.setOnClickListener(this);
- rb_4.setOnClickListener(this);
- }
//重写监听方法
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.rb_01:
- select(0);
- break;
- case R.id.rb_02:
- select(1);
- break;
- case R.id.rb_03:
- select(2);
- break;
- case R.id.rb_04:
- select(3);
- break;
- }
- }
//管理Fragment的方法,在监听事件中调用
- private void select(int i) {
- FragmentManager fm = getSupportFragmentManager(); //获得Fragment管理器
- FragmentTransaction ft = fm.beginTransaction(); //开启一个事务
- hidtFragment(ft); //隐藏Fragment的方法,先判断fragment是否为空,如果不为空则隐藏Fragment
- switch (i) {//点击切换fragment,如果fragment为空,则创建,如果不为空,就显示
- case 0:
- if (firstFragment == null) {
- firstFragment = new Fragment1();
- ft.add(R.id.FramLaout, firstFragment);
- } else {
- ft.show(firstFragment);
- }
- break;
- case 1:
- if (secondFragment == null) {
- secondFragment = new Fragment2();
- ft.add(R.id.FramLaout, secondFragment);
- } else {
- ft.show(secondFragment);
- }
- break;
- case 2:
- if (thirdFragment == null) {
- thirdFragment = new Fragment3();
- ft.add(R.id.FramLaout, thirdFragment);
- } else {
- ft.show(thirdFragment);
- }
- break;
- case 3:
- if (fourFragment == null) {
- fourFragment = new Fragment4();
- ft.add(R.id.FramLaout, fourFragment);
- } else {
- ft.show(fourFragment);
- }
- break;
- }
- ft.commit(); //提交事务
- }
//隐藏所有的Fragment,在上面会用到
- private void hidtFragment(FragmentTransaction fragmentTransaction) {
- if (firstFragment != null) {
- fragmentTransaction.hide(firstFragment);
- }
- if (secondFragment != null) {
- fragmentTransaction.hide(secondFragment);
- }
- if (thirdFragment != null) {
- fragmentTransaction.hide(thirdFragment);
- }
- if (fourFragment != null) {
- fragmentTransaction.hide(fourFragment);
- }
- }
//设置第一个页面为默认页面
- private void initDefultView() {
- FragmentManager fm = getSupportFragmentManager();
- FragmentTransaction ft = fm.beginTransaction();
- firstFragment = new Fragment1();
- ft.add(R.id.FramLaout, firstFragment);
- ft.commit();
- }