一、首先创建一个activity,开辟一块帧布局,用来放置fragment,写四个单选按钮用来控制切换。
二、
private MyFragment f1, f2, f3, f4, index; Bundle bundle; FragmentTransaction transaction; FragmentManager manager; RadioGroup rg;(index 总是指向当前fragment)
获取到fragmentManager,初始化fragment:
f1 = new MyFragment(); bundle = new Bundle(); bundle.putInt("color", Color.BLUE); f1.setArguments(bundle); index = f1; f2 = new MyFragment(); bundle = new Bundle(); bundle.putInt("color", Color.RED); f2.setArguments(bundle); f3 = new MyFragment(); bundle = new Bundle(); bundle.putInt("color", Color.GREEN); f3.setArguments(bundle); f4 = new MyFragment(); bundle = new Bundle(); bundle.putInt("color", Color.GRAY); f4.setArguments(bundle); transaction = manager.beginTransaction(); transaction.add(R.id.frame, f1).add(R.id.frame, f2).add(R.id.frame, f3).add(R.id.frame, f4).hide(f2) .hide(f3).hide(f4).show(f1).commit();
ok,到这里 fragment就显示出来了,然后写个方法给单选按钮的监听,根据单选按钮可以切换fragment。
private void switchFragment(MyFragment from, MyFragment to) { if (from == to) return; transaction = manager.beginTransaction(); //.setCustomAnimations(R.anim.set, R.anim.setto); transaction.hide(from).show(to).commit(); index=to; }
然后设置给监听:
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb1: switchFragment(index, f1); // Intent intent1 = new Intent(MainActivity.this, Main2Activity.class); // intent1.putExtras(new Bundle()); // startActivity(intent1); break; case R.id.rb2: switchFragment(index, f2); break; case R.id.rb3: switchFragment(index, f3); break; case R.id.rb4: switchFragment(index, f4); break; } } });