private QuotesChildCollectFragment f2;
private QuotesChildCollectFragment f1;
private void setTabSelection(int index) {
//getSupportFragmentManager() ,getParentFragmentManager()
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
hideFragment(ft);
switch (index) {
case IConstants.COLLECT_CONTRACT:
if (f1== null) {
f1 = QuotesChildCollectFragment.newInstance(index);
ft.add(R.id.fl_container, f1);
} else {
ft.show(f1);
}
break;
case IConstants.COLLECT_BIBI:
if (f2 == null) {
f2 = QuotesChildCollectFragment.newInstance(index);
ft.add(R.id.fl_container, f2);
}
ft.show(f2);
break;
}
ft.commit();
}
//隐藏所有的fragment
private void hideFragment(FragmentTransaction transaction){
if(f1 != null){
transaction.hide(f1);
}
if(f2 != null){
transaction.hide(f2);
}
}
调用时默认选择一个
setTabSelection(IConstants.COLLECT_CONTRACT);
切换时:
mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
if (checkedId == R.id.rb_default_data_contract) {
setTabSelection(IConstants.COLLECT_CONTRACT);
}else if(checkedId == R.id.rb_default_data_bibi) {
setTabSelection(IConstants.COLLECT_BIBI);
}
});
布局要求:用FrameLayout装载fragment
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fl_container"/>
当fragment个数不固定或者需要从网络请求中获取fragment个数时(一般fragment内容一样),可以使用TabLayout或者第三方的库MagicIndicator(https://github.com/hackware1993/MagicIndicator)
网友评论