前言
如果你之前没接触过的话,建议先下载demo,对比本文进行学习;
如果你向我一样,总是忘记,那就动动小手收藏一下吧~~~
demo: https://github.com/liuleshuai/NavigationMenuBar
爱你
干货
现在的App底部一般都有一个可切换的菜单,通常使用有以下5种方式实现:
TabHost(过时)
Radiobutton(自定义)
FragmentTabHost
TabLayout(5.0新增)
BottomNavigationView(5.0新增)
1.TabHost
它添加的是Activity而不像上面那些全部使用Fragment来显示内容。
过时,不推荐使用,略...
2.Radiobutton
不推荐,略...
3.FragmentTabHost
依赖
布局
底部菜单栏的布局一般如下所示:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
android:id="@+id/realcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff" >
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" >
FragmentTabHost的id是需要使用安卓自带的id,必须设置为@android:id/tabhost。
FragmentTabHost中的FrameLayout也需要使用安卓自带的id,@android:id/tabcontent。
另外,需要添加一个菜单Item的布局。
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
android:id="@+id/tab_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:gravity="center"
android:textColor="#ffffff"
android:textSize="12sp" />
代码
绑定
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
//绑定Fragment
mTabHost.setup(this, getSupportFragmentManager(), R.id.realcontent);
//绑定viewpager
// mTabHost.setup(this, getSupportFragmentManager(), R.id.pager);
设置菜单选项卡
for (int i = 0; i < count; i++) {
// 给每个Tab按钮设置标签、图标和文字
TabHost.TabSpec tabSpec = mTabHost.newTabSpec(textViewArray[i])
.setIndicator(g