转载请注明出处: http://blog.csdn.net/like_program/article/details/53576927
微信想必大家都很熟悉了,它的底部菜单栏和显示未读消息数量功能,被很多 app 模仿,这篇博客就来带领大家,一步一步实现底部菜单栏,并且在底部菜单栏显示未读消息数量。
我们先来看下最终效果图。
最终效果图
1.底部菜单栏
2.显示未读消息数量
1.实现底部菜单栏
我们先来实现底部菜单栏。
打开 Android Studio,新建 TabTest 项目。
底部菜单栏是由 4 个 tab 组成,我们先来实现 tab 的布局,在 layout 目录下新建 view_tab.xml ,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="@+id/iv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/tab_wechat_normal"/>
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微信"/>
</LinearLayout>
</RelativeLayout>
嗯,布局看上去有些繁琐。。。不过为了后面布局修改方便,暂时先无视这些。。。
tab 布局完成后,我们接着实现底部菜单栏,底部菜单栏,我们使用 FragmentTabHost 来实现。
修改 activity_main.xml 文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
tools:context="com.example.tabnews.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- Fragment 容器 -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<!-- 底部菜单栏 -->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
没有使用过 FragmentTabHost 的同学看布局文件可能会有些晕。为了便于大家理解,我简单的画张图。
我们可以看到,最外层的控件就是 FragmentTabHost,在 FragmentTabHost 里面从上至下,依次是
tabcontent 和 tabs。这里要注意下,控件的 id 必须是 Android 提供的标准 id , 即 @android:id。
- FragmentTabHost 用来托管 Fragment 和 TabWidget(底部菜单栏),所以我们把它的 id 指定为
@android:id/tabhost
- FrameLayout 用来放置 Fragment,也就是具体展示的内容,所以我们把它的 id 指定为
@android:id/tabcontent
- TabWidget 用来放置底部菜单栏,底部菜单栏有很多 tab。所以我们把它的 id 指定为
@android:id/tabs
当点击不同的 tab 时,对应的 Fragment 就会被切换到 FrameLayout 中。
布局文件完成后,我们修改 MainActivity.java,代码如下:
package com.example.tabtest;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;