现在一般的app都使用底部菜单栏,那具体怎么实现的呢!我们就来看看
首先给大家展示一下布局文件
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 android:orientation="vertical" android:layout_width="match_parent"
3 android:layout_height="match_parent">
4 <FrameLayout
5 android:id="@+id/realtabcontent"
6 android:layout_width="fill_parent"
7 android:layout_height="0dip"
8 android:layout_weight="1"
9 android:background="@color/white" />
10
11
12 <LinearLayout
13 android:layout_width="match_parent"
14 android:layout_height="wrap_content"
15 android:layout_gravity="bottom"
16 android:orientation="vertical">
17
18 <View
19 android:layout_width="match_parent"
20 android:layout_height="1px"
21 android:background="@color/color_home_tab_line" />
22
23 <android.support.v4.app.FragmentTabHost
24 android:id="@android:id/tabhost"
25 android:layout_width="fill_parent"
26 android:layout_height="wrap_content"
27 android:background="@color/et_divider_disable">
28
29 <FrameLayout
30 android:id="@android:id/tabcontent"
31 android:layout_width="0dp"
32 android:layout_height="0dp"
33 android:layout_weight="0" />
34 </android.support.v4.app.FragmentTabHost>
35
36 </LinearLayout>
37 </LinearLayout>
接下来就是怎么使用了,其实比较简单,我们就看代码吧!
//数据
private int mImageViewArray[] = {R.drawable.home_tab1, R.drawable.home_tab2, R.drawable.home_tab3};
private String mTextviewArray[] = {"首页", "设置","我的"};
private Class fragmentArray[] = {Fragment1.class, Fragment2.class, Fragment3.class}; //初始化以及设置数据
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
int count = fragmentArray.length;
for (int i = 0; i < count; i++) {
TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
.setIndicator(getTabItemView(i));
mTabHost.addTab(tabSpec, fragmentArray[i], null);
mTabHost.getTabWidget().getChildAt(i)
.setBackgroundResource(R.drawable.bg_tbitem);
}
mTabHost.setCurrentTabByTag(mTextviewArray[0]);
mTabHost.getTabWidget().setDividerDrawable(null); mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String s) { }
}); /**
* 项的样式
*
* @param index 第几个
* @return 每一个Tab样式
*/
private View getTabItemView(int index) {
View view = layoutInflater.inflate(R.layout.tab_home_item, null);
ImageView imageView = (ImageView) view.findViewById(R.id.icon);
imageView.setImageResource(mImageViewArray[index]);
TextView textView = (TextView) view.findViewById(R.id.name);
textView.setText(mTextviewArray[index]);
return view;
}
对了,其中图片我们都设置成了selector,才有点击变色的效果
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_jiance_pre" android:state_pressed="false" android:state_selected="true" />
<item android:drawable="@drawable/btn_jiance_nor" android:state_focused="false" android:state_pressed="false" android:state_selected="false" />
<item android:drawable="@drawable/btn_jiance_pre" android:state_focused="true" android:state_pressed="true" />
</selector>