应用经常用到底部导航栏,早前使用过RadioGroup + FrameLayout实现或者RadioGroup +: viewpage实现,现在基本使用FragmentTabHost + FrameLayout来实现,因为使用起来简单易用。下面写一个小例子简要地总结一下这个组合。
首先,看一下例子的最终运行效果图
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " android: layout_width=" match_parent " android: layout_height=" match_parent " 面向android:=按怪薄北? & lt; FrameLayout android: id=癅 + id/realtabcontent” android: layout_width=" match_parent " android: layout_height=" 0 dp” android: layout_weight=" 1 " android:背景=癅color/bg_color”/比; & lt; android.support.v4.app.FragmentTabHost android: id=" @android: id/tabhost” android: layout_width=" match_parent " android: layout_height=" wrap_content " android:背景=" @color/白”比; & lt; FrameLayout android: id=" @android: id/tabcontent” android: layout_width=" 0 dp” android: layout_height=" 0 dp” android: layout_weight=" 0 "/比; & lt;/android.support.v4.app.FragmentTabHost> & lt;/LinearLayout> >之前
布局大体分为两部分,上面的FrameLayout代表是显示内容部分,下面的FragmentTabHost代表是导航栏部分。注意:FragmentTabHost的id和其内部的FrameLayout的id必须是系统的id。
<强>第二步,>强,可以记住三个步骤:(1)设置(…)可以理解为,初始化底部导航和内容页面连接,(2)新建TabSpec可以理解为初始化底部菜单项,(3)addTab(…)可以理解为把菜单和内容添加到控件中。下面看一下代码:
公开课MainActivity延伸AppCompatActivity { 私人LayoutInflater mInflater; 私人FragmentTabHost mTabHost; 私人ArrayListtabDataList=new ArrayList<比;(5); @Override 保护空白> & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " android:取向=按怪薄? android: layout_width=" match_parent " android: layout_height=" match_parent " android: paddingTop=" 3 dp” android: paddingBottom=" 3 dp” android: layout_gravity="中心" android:重力="中心"的在 & lt; ImageView android: id=癅 + id/iv_tab_icon” android: layout_width=" wrap_content " android: layout_height=" wrap_content "/比; & lt; TextView android: id=癅 + id/tv_tab_text” android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:输入textColor=" @color/tabTextColor” android: layout_marginTop=" 2 dp/比; & lt;/LinearLayout> >之前 HomeFragment.java
公开课HomeFragment延伸片段{ @Nullable @Override 公众视野> & lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; LinearLayout xmlns: android=" http://schemas.android.com/apk/res/android " android:取向=按怪薄盿ndroid: layout_width=癿atch_parent” android: layout_height=" match_parent " android:重力="中心"的在 & lt; TextView android: layout_width=" wrap_content " android: layout_height=" wrap_content " android:输入textColor=" @color/themeColor” android:文本=癅string/tabHome”/比; & lt;/LinearLayout> >之前写完如上代码的运行效果如下: