//定义变量 private ArrayList<Fragment> fragmentList = new ArrayList<Fragment>(); private RadioGroup group; private FragmentManager supportFragmentManager; String TAG = "wzq"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化组件 group = (RadioGroup) findViewById(R.id.group); initFragment(); supportFragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction(); fragmentTransaction.add(R.id.fl_main, fragmentList.get(0)).commit(); group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { //要切换fragment @Override public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) { Log.e(TAG, "onCheckedChanged 点击的id:" + i); switch (i) { case R.id.but1: supportFragmentManager.beginTransaction().replace(R.id.fl_main, new MainFragment()).commit(); Log.e(TAG, "onCheckedChanged: 点击button1"); break; case R.id.but2: getSupportFragmentManager().beginTransaction().replace(R.id.fl_main, new MainFragment()).commit(); Log.e(TAG, "onCheckedChanged: 点击button2"); break; case R.id.but3: getSupportFragmentManager().beginTransaction().replace(R.id.fl_main, new MainFragment()).commit(); Log.e(TAG, "onCheckedChanged: 点击button3" ); break; case R.id.but4: getSupportFragmentManager().beginTransaction().replace(R.id.fl_main, new MainFragment()).commit(); break; case R.id.but5: getSupportFragmentManager().beginTransaction().replace(R.id.fl_main, new MainFragment()).commit(); break; } } }); } //准备好所有的fragment private void initFragment() { for (int i = 0; i < 5; i++) { fragmentList.add(new MainFragment()); } }
MainActivity
最新推荐文章于 2024-09-16 00:15:00 发布