Fragment不使用ViewPager也可以第一次加载Activity就可以显示Fragment,如果使用ViewPager可以设置监听器和适配器进行第一次加载Activity就可以显示Fragment,现在把ViewPager去掉也可以实现第一次加载Activity就可以显示Fragment。
public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
private FrameLayout frame;
private RadioGroup rg;
private RadioButton rb_shouye,rb_gengduo,rb_shezhi,rb_wode;
private FragmentManager manager;
private List<Fragment> fragmentList;// 存储所有的Fragment
private int firstFragment = 0; //第一次加载的Fragment
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化集合 往集合中添加Fragment
addFragmentList();
//初始化控件
initView();
//显示Fragment
ShowFragment(firstFragment);
}
private void initView() {
frame = findViewById(R.id.frame);
rg = findViewById(R.id.rg);
rb_shouye = findViewById(R.id.shouye);
rb_gengduo = findViewById(R.id.gengduo);
rb_shezhi = findViewById(R.id.shezhi);
rb_wode = findViewById(R.id.wode);
manager = getSupportFragmentManager();
//设置监听
rg.setOnCheckedChangeListener(this);
}
private void ShowFragment(int position) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.frame,fragmentList.get(position));
transaction.commit();
}
private void addFragmentList() {
fragmentList = new ArrayList<>();
fragmentList.add(new HomeFragment());
fragmentList.add(new GengduoFragment());
fragmentList.add(new ShezhiFragment());
fragmentList.add(new WodeFragment());
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId){
case R.id.shouye:
ShowFragment(0);
rb_shouye.setChecked(true);
break;
case R.id.gengduo:
ShowFragment(1);
rb_gengduo.setChecked(true);
break;
case R.id.shezhi:
ShowFragment(2);
rb_shezhi.setChecked(true);
break;
case R.id.wode:
ShowFragment(3);
rb_wode.setChecked(true);
break;
}
}
}
第一次运行的截图
点击后
若有看不懂的地方也可以去下载我的源码
链接