安卓底部导航我使用的是FrameLayout和RadioGroup的组合,布局代码如下:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/tabs_rg" />
<RadioGroup
android:id="@+id/tabs_rg"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/today_tab"
style="@style/Custom.TabRadioButton"
android:checked="true"
android:drawableTop="@drawable/tab_sign_selector"
android:text="首页" />
<RadioButton
android:id="@+id/record_tab"
style="@style/Custom.TabRadioButton"
android:drawableTop="@drawable/tab_record_selector"
android:text="社区" />
<RadioButton
android:id="@+id/voice_tab"
style="@style/Custom.TabRadioButton"
android:drawableTop="@drawable/tab_voice_selector" />
<RadioButton
android:id="@+id/contact_tab"
style="@style/Custom.TabRadioButton"
android:drawableTop="@drawable/tab_contact_selector"
android:text="发现" />
<RadioButton
android:id="@+id/settings_tab"
style="@style/Custom.TabRadioButton"
android:drawableTop="@drawable/tab_setting_selector"
android:text="我的" />
</RadioGroup>
根据选中的按钮不同,动态切换内容:
public RadioGroup mTabRadioGroup = findViewById(R.id.tabs_rg);
private SparseArray<Fragment> mFragmentSparseArray= new SparseArray<>();
mFragmentSparseArray.append(R.id.today_tab, FirstFragment.newInstance("首页"));
mFragmentSparseArray.append(R.id.record_tab, SecondFragment.newInstance("社区"));
mFragmentSparseArray.append(R.id.voice_tab,VoiceFragment.newInstance("翻译"));
mFragmentSparseArray.append(R.id.contact_tab, ThirdFragment.newInstance("发现"));
mFragmentSparseArray.append(R.id.settings_tab, FourthFragment.newInstance("我的"));
mTabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// 具体的fragment切换逻辑可以根据应用调整,例如使用show()/hide()
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
mFragmentSparseArray.get(checkedId)).addToBackStack(null).commit();
}
});
//默认显示第一页
fragment = new FirstFragment("第一页");
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,
fragment).commit();
}
//这是上方调用的一个方法,其他的也和此类似
public static FirstFragment newInstance(String param1) {
FirstFragment fragment = new FirstFragment(param1);
Bundle args = new Bundle();//封装数据
args.putString(ARG_SHOW_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
FirstFragment继承的是Fragment,这里面有一个onCreateView方法是加载布局的:之前在onCreate里面加载的布局现在都写在这里面。