Android使用fragment实现底部导航栏切换界面
效果图
首页 大学 宝贝记 广场 我的1.设计底部导航栏的布局,我选择的是常规界面的导航栏模式,上面图标,下面文字
创建bottom_layout.xml
<?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:orientation="vertical"
android:gravity="center">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:id="@+id/bottom_icon"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#565656"
android:textSize="10sp"
android:id="@+id/bottom_text" />
2.创建BottomLayout类继承自LinearLayout,动态的控制bottom_layout显示界面
public void setNormalImage(int normalIcon){
this.normalIcon = normalIcon;
ivIcon.setImageResource(normalIcon);
}
public void setFocusedImage(int focusedIcon){
this.focusedIcon = focusedIcon;
}
public void setTvText(String text){
tvText.setText(text);
}
public void setFocused(boolean isFocused){
this.isFocused = isFocused;
if(isFocused){
ivIcon.setImageResource(focusedIcon);
tvText.setTextColor(Color.parseColor("#02b5bc"));
}else{
ivIcon.setImageResource(normalIcon);
tvText.setTextColor(Color.BLACK);
}
}
3.在activity_main.xml中动态引用4个这样的布局,注意修改Bottom_layout的路径,底部导航栏上方是存放fragment切换界面的容器
<FrameLayout
android:id="@+id/frameLayout_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="11"
>
</FrameLayout>
四个如下
<com.example.qiaolulu.qiaofragment.BottomLayout
android:id="@+id/square"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
</com.example.qiaolulu.qiaofragment.BottomLayout>
4.创建子界面5个activity,他们都继承自Fragment
public class Babyextends Fragment{
@Nullable
@Override
public ViewonCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//加载你设计要显示的界面
View view = inflater.inflate(R.layout.baby,null);
return view;
}
}
5.MainActivity继承自FragmentActivity,为底部导航栏设置默认和选中状态下的文字颜色和图片,对每一个菜单项添加监听事件,使用FragmentManager和FragmentTransaction进行界面切换
fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction =fragmentManager.beginTransaction();
firstPage =new FirstPage();
transaction.add(R.id.frameLayout_container,firstPage);
transaction.commit();