FrameLayout的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<RadioGroup
android:id="@+id/rg_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="@drawable/home_bottom_parent_bg"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_home"
style="@style/MainButtonStyle"
android:drawableTop="@drawable/home_button_selector"
android:text="首页" />
</RadioGroup>
</LinearLayout>
在drawable文件夹下,建立selector文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/main_home" android:state_checked="false"></item>
<item android:drawable="@drawable/main_home_press" android:state_checked="true"></item>
</selector>
在values文件夹下,对styles文件,添加风格描述:
<style name="MainButtonStyle">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">1</item>
<item name="android:button">@null</item>
<item name="android:textColor">@drawable/bottom_button_text_selector</item>
<item name="android:textSize">10sp</item>
<item name="android:gravity">center</item>
</style>
初始化RadioGroup rgMain,并设置监听器:
//装fragment的实例集合
ArrayList<BaseFragment> fragments;
int position = 0;
//缓存Fragment或上次显示的Fragment
Fragment tempFragment;
rgMain.check(R.id.rb_home);
rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i) {
case R.id.rb_home: //首页
position = 0;
break;
}
//根据位置得到相应的Fragment
BaseFragment baseFragment = getFragment(position);
/**
* 第一个参数: 上次显示的Fragment
* 第二个参数: 当前正要显示的Fragment
*/
switchFragment(tempFragment, baseFragment);
}
});
切换Fragment:
private void switchFragment(Fragment fragment, BaseFragment nextFragment) {
if (tempFragment != nextFragment) {
tempFragment = nextFragment;
if (nextFragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//判断nextFragment是否添加成功
if (!nextFragment.isAdded()) {
//隐藏当前的Fragment
if (fragment != null) {
transaction.hide(fragment);
}
//添加Fragment
transaction.add(R.id.frameLayout, nextFragment).commit();
} else {
//隐藏当前Fragment
if (fragment != null) {
transaction.hide(fragment);
}
transaction.show(nextFragment).commit();
}
}
}
}