底下菜单栏Tab的实现

有两种方式实现:1.自定义. 2.用系统提供

1.自定义方式

①写好整体布局

分为两大部分,上面用帧布局来展示fragment,下面为组合控件作为Tab进行主页面的切换.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"  >
    <!--帧布局,用于放置Fragment-->
    <FrameLayout
        android:id="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"  />
    <!--红色线条-->
    <View 
        android:layout_width="match_parent"
        android:layout_height="4dp"
        android:background="#BB1F35" />
    <!-- 组合控件 -->
    <include 
        android:id="@+id/bottom_bar"
        layout="@layout/bottom_bar" />
</LinearLayout>

②组合控件,Tab的制作

根据自己的需要进行设计,自定义控件

Java代码

public class BottomBar extends LinearLayout implements View.OnClickListener {

    private ImageView frag_main_iv;
    private TextView frag_main;

    private ImageView frag_category_iv;
    private TextView frag_category;

    private ImageView frag_shopcar_iv;
    private TextView frag_shopcar;

    private ImageView frag_mine_iv;
    private TextView frag_mine;
    private IBottomBarItemClickListener mListener;
    private int mCurrentTabId=-1;

    //程序员自己new控件的时候使用的
    public BottomBar(Context context) {
        super(context);
    }

    //将控件放到xml布局中 系统在xml布局文件中加载控件的时候就会默认调用该构造器
    public BottomBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    //获取子控件  并且为子控件设置样式
    //该方法用来告诉我们 布局转换成控件已经转换完毕了
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        findViewById(R.id.frag_main_ll).setOnClickListener(this);
        findViewById(R.id.frag_category_ll).setOnClickListener(this);
        findViewById(R.id.frag_shopcar_ll).setOnClickListener(this);
        findViewById(R.id.frag_mine_ll).setOnClickListener(this);
        frag_main_iv = (ImageView) findViewById(R.id.frag_main_iv);
        frag_category_iv = (ImageView) findViewById(R.id.frag_category_iv);
        frag_shopcar_iv = (ImageView) findViewById(R.id.frag_shopcar_iv);
        frag_mine_iv = (ImageView) findViewById(R.id.frag_mine_iv);
        frag_main = (TextView) findViewById(R.id.frag_main);
        frag_category = (TextView) findViewById(R.id.frag_category);
        frag_shopcar = (TextView) findViewById(R.id.frag_shopcar);
        frag_mine = (TextView) findViewById(R.id.frag_mine);
        //模拟用户点击了首页
        findViewById(R.id.frag_main_ll).performClick();
    }

    /**
     * Indicators 指示器
     */
    private void changeIndicators(int viewId) {
        frag_main_iv.setSelected(viewId == R.id.frag_main_ll);
        frag_main.setSelected(viewId == R.id.frag_main_ll);
        frag_category_iv.setSelected(viewId == R.id.frag_category_ll);
        frag_category.setSelected(viewId == R.id.frag_category_ll);

        frag_shopcar_iv.setSelected(viewId == R.id.frag_shopcar_ll);
        frag_shopcar.setSelected(viewId == R.id.frag_shopcar_ll);
        frag_mine_iv.setSelected(viewId == R.id.frag_mine_ll);
        frag_mine.setSelected(viewId == R.id.frag_mine_ll);
    }

    @Override
    public void onClick(View view) {
        //如果当前是点击某个按钮了 就要做一个拦截
        //每次都要获取点击的item的id的优化
        int mTabId=view.getId();
        if (mCurrentTabId==mTabId){
            return;
        }
        switch (mTabId) {
            case R.id.frag_main_ll:
            case R.id.frag_category_ll:
            case R.id.frag_shopcar_ll:
            case R.id.frag_mine_ll:
                changeIndicators(mTabId);
                if (mListener != null) {
                    mListener.onItemClick(mTabId);
                }
                break;
        }
        //记录当前点击的是哪个View
        mCurrentTabId=mTabId;
    }

    public void setIBottomBarItemClickListener(IBottomBarItemClickListener listener) {
        this.mListener = listener;
    }
}

xml代码

<?xml version="1.0" encoding="utf-8"?>
<com.it520.jdmall03.ui.BottomBar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:orientation="horizontal"  >

    <LinearLayout
        android:id="@+id/frag_main_ll" 
        style="@style/bottom_ll_style" >

        <ImageView
            android:id="@+id/frag_main_iv"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/home_bot_bar" />

        <TextView
            android:id="@+id/frag_main"
            style="@style/bottom_text_style"
            android:text="@string/frag_main" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/frag_category_ll" 
        style="@style/bottom_ll_style" >

        <ImageView
            android:id="@+id/frag_category_iv"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/category_bot_bar" />

        <TextView
            android:id="@+id/frag_category"
            style="@style/bottom_text_style"
            android:text="@string/frag_category" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/frag_shopcar_ll" 
        style="@style/bottom_ll_style" >

        <ImageView
            android:id="@+id/frag_shopcar_iv"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/shopcar_bot_bar" />

        <TextView
            android:id="@+id/frag_shopcar"
            style="@style/bottom_text_style"
            android:text="@string/frag_shopcar" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/frag_mine_ll"
        style="@style/bottom_ll_style" >

        <ImageView
            android:id="@+id/frag_mine_iv"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/mine_bot_bar" />

        <TextView
            android:id="@+id/frag_mine"
            style="@style/bottom_text_style"
            android:text="@string/frag_mine" />
    </LinearLayout>

</com.it520.jdmall03.ui.BottomBar>

效果如下

undertabimg1.jpg

整体效果如下

undertabimg2.jpg

每一个bottom都设置了背景选择器,当选中时会更变颜色,可以更好地看出是哪个按钮被选中,代码中还引用了Velues文件夹中资源件里的属性,这里就不一一展示了.

③功能的实现

布局设计完成后要进行功能的实现,就是按下不同的Tab,页面进行切换
首先要创建好需要的Fragment,然后通过点击Tab按钮进行Fragment的切换
代码如下:

public class MainActivity extends BaseActivity implements IBottomBarItemClickListener {

    private ArrayList<BaseFragment> mFragments;
    private BottomBar mBottomBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(null);
        setContentView(R.layout.activity_main);
        initViews();
        initFragments();
        changeFragment(mFragments.get(0));
    }

    private void initViews() {
        mBottomBar =(BottomBar) findViewById(R.id.bottom_bar);
        mBottomBar.setIBottomBarItemClickListener(this);
    }

    private void initFragments(){
        mFragments=new ArrayList<>();
        mFragments.add(new HomeFragment());
        mFragments.add(new CategoryFragment());
        mFragments.add(new ShopcarFragment());
        mFragments.add(new MyJdFragment());
    }

    /**
     * 点击底部栏切换Fragment--->事务
     * */
    private void changeFragment(BaseFragment f){
        FragmentManager fManager = getSupportFragmentManager();
        FragmentTransaction transaction = fManager.beginTransaction();
        //add 往容器里面不断的添加东西  此刻你可以认为容器就是一个队列
        //remove  不断的往容器里面移除Fragment
        // show/hide   就是容器里面已经有某个Fragment了 只能显示隐藏
        //                  此刻Fragment的生命周期是没变化     onHiddenChanged
        //replace  不管容器里面有多少Fragment 都会销毁掉  再添加新的Fragment
        //attach/detach  处理是否关联Fragment内部的布局  Fragment还在
        transaction.replace(R.id.top_bar,f);
        transaction.commitAllowingStateLoss();
    }

    /**
     * 底部栏点击的item方法回调
     * */
    @Override
    public void onItemClick(int viewId) {
        switch (viewId) {
            case R.id.frag_main_ll:
                changeFragment(mFragments.get(0));
                break;
            case R.id.frag_category_ll:
                changeFragment(mFragments.get(1));
                break;
            case R.id.frag_shopcar_ll:
                changeFragment(mFragments.get(2));
                break;
            case R.id.frag_mine_ll:
                changeFragment(mFragments.get(3));
                break;
        }
    }

}

完成,终效果如下:

undertabimg3.gif

2.利用系统提供的控件FragmentTabHost

①写好主页的布局

分为两部分,上面用FrameLayout来展示Fragment,下面为v4包下的FragmentTabHost控件,这是google提供的菜单栏控件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/main_framelayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

    <android.support.v4.app.FragmentTabHost
        android:id="@+id/main_fragmenttabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </android.support.v4.app.FragmentTabHost>
</LinearLayout>

②功能实现

在MainActivity中找到控件,按照使用方法给控件添加自己需要的样式

item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
    android:gravity="center_horizontal">

    <ImageView
        android:id="@+id/item_tab_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/tab_my_selected"/>

    <TextView
        android:id="@+id/item_tab_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我的"/>
</LinearLayout>

java代码

public class MainActivity extends AppCompatActivity {

    private FrameLayout mMainFramelayout;
    private MyFragmentTabHost mMainTabhost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initTabHost();
    }

    //tabHost切换tab
    private void initTabHost() {
        //最基本使用方式
        //        //1.初始化,传入需要的参数
        //        mMainTabhost.setup(getApplicationContext(), getSupportFragmentManager(), R.id.main_framelayout);
        //        //2.开始设置tabhost
        //        //设置标签,用来表示不同的tab
        //        TabHost.TabSpec tabSpec = mMainTabhost.newTabSpec("1");
        //        //设置指示器,即为显示按钮的布局
        //        tabSpec.setIndicator("新闻");
        //        NewsFragment newsFragment = new NewsFragment();
        //        //参数:标签,fragment对象,需要传入的数据
        //        mMainTabhost.addTab(tabSpec, newsFragment.getClass(), null);
        //
        //利用for循环进行添加可以减少代码量
        mMainTabhost.setup(getApplicationContext(), getSupportFragmentManager(), R.id.main_framelayout);
        int[] resIds = {R.drawable.tab_news, R.drawable.tab_va, R.drawable.tab_topic, R.drawable.tab_my};
        String[] tabTexts = {"新闻", "直播", "话题", "我的"};
        Class[] fragmentClazz = {new NewsFragment().getClass(), new VaFragment().getClass(), new TopicFragment().getClass(), new MeFragment().getClass()};
        for (int i = 0; i < resIds.length; i++) {
            TabHost.TabSpec tabSpec = mMainTabhost.newTabSpec(String.valueOf(i));
            View inflate = View.inflate(getApplicationContext(), R.layout.item_tab, null);
            tabSpec.setIndicator(inflate);
            ImageView ivTab = (ImageView) inflate.findViewById(R.id.item_tab_iv);
            TextView tvTab = (TextView) inflate.findViewById(R.id.item_tab_tv);
            ivTab.setImageResource(resIds[i]);
            tvTab.setText(tabTexts[i]);

            mMainTabhost.addTab(tabSpec, fragmentClazz[i], null);
        }
        
    }

    private void initView() {
        mMainFramelayout = (FrameLayout) findViewById(R.id.main_framelayout);
        mMainTabhost = (MyFragmentTabHost) findViewById(R.id.main_tabhost);
    }
}

基本使用已经完成,效果如下图:

undertabimg4.gif

③优化

通过观察源代码发现,点击tab切换Fragment的方式为detach和attach两个方法,这样会导致每次切换Fragment时都会重新加载,不能保留客户在界面上的操作,而我的业务需求是最好能保留客户的操作,所以我重写了这个类,并做了一点修改.

首先创建一个类MyFragmentTabHost,继承TabHost,然后找到系统提供的FragmentTabHost类,全部复制一份,粘贴到自己的类中,再进行修改下面方法,把detach和attach,改为hide和show

 @Nullable
    private FragmentTransaction doTabChanged(@Nullable String tag,
            @Nullable FragmentTransaction ft) {
        final TabInfo newTab = getTabInfoForTag(tag);
        if (mLastTab != newTab) {
            if (ft == null) {
                ft = mFragmentManager.beginTransaction();
            }

            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
//                    ft.detach(mLastTab.fragment);
                    ==ft.hide(mLastTab.fragment)==;
                }
            }

            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(mContext,
                            newTab.clss.getName(), newTab.args);
                    ft.add(mContainerId, newTab.fragment, newTab.tag);
                } else {
//                    ft.attach(newTab.fragment);
                    ==ft.show(newTab.fragment);==

                }
            }

修改完成后,再在布局中修改引用的控件类型,改成自己的类就可以了.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.simon.newwangyi.activity.MainActivity">

    <FrameLayout
        android:id="@+id/main_framelayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        />

    <com.simon.newwangyi.view.MyFragmentTabHost
        android:id="@+id/main_tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </com.simon.newwangyi.view.MyFragmentTabHost>
</LinearLayout>

完成.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容