底部菜单栏demo实现

一、简介

实现效果图如下:

屏幕快照 2018-07-30 下午3.35.03.png

类似美团主页的底部菜单栏,禁止横向滑动,可以点击tab切换fragment。

采用的框架为Material Design中的tabLayout+ViewPager实现Fragment的切换

二、布局/资源文件

在xml中定义一个tab背景选中和没选中时采用不同的图片,以及不同的字体颜色

2.1 tab的ImageButton背景选择器

selector_home_tab.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_home_red" android:state_selected="true" />
    <item android:drawable="@drawable/ic_home_gray" android:state_selected="false" />
</selector>

selector_surround.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_surround_gray" android:state_selected="false" />
    <item android:drawable="@drawable/ic_surround_red" android:state_selected="true" />
</selector>

其余三个标签类似

2.2 tab中文字颜色背景选择器

selector_tab_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/colorRed" android:state_selected="true"/>
    <item android:color="@color/colorDefaultText" android:state_selected="false"/>
</selector>

2.3 tab item的布局文件

tab_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="5dp">
    <LinearLayout
        android:layout_width="@dimen/tab_width"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <ImageButton
            android:id="@+id/tab_btn"
            android:layout_width="match_parent"
            android:layout_height="@dimen/image_button_height"
            android:background="@drawable/ic_find_gray"
            android:clickable="false"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="@dimen/tab_text_height"
            android:text="发现"
            android:textColor="@drawable/selector_tab_text"
            android:textAlignment="center"
            android:id="@+id/tab_text"/>
    </LinearLayout>

</LinearLayout>

2.4 Fragment布局文件

这次demo没有写好几种Fragment,而是用同一种Fragment。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="fragment"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/frag_text"/>
</android.support.constraint.ConstraintLayout>

2.5 MainActivity布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.meituan.huangdanyang.practise.CustomViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="450dp"
        android:orientation="vertical" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorBoarder"
        app:layout_constraintBottom_toTopOf="@+id/menu" />

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/tab_layout_height"
        android:id="@+id/menu"
        app:layout_constraintBottom_toBottomOf="parent"
        app:tabIndicatorHeight="0dp"/>
</android.support.constraint.ConstraintLayout>

三、java文件

3.1 HomeFragment.java

package com.meituan.huangdanyang.practise;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class HomeFragment extends BaseFragment {

    private final static String ARG_PARAM1 = "text";
    private String text;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param text Parameter text.
     * @return A new instance of fragment HomeFragment.
     */

    public static HomeFragment newInstance(String text) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, text);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            text = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        TextView textView = view.findViewById(R.id.frag_text);
        textView.setText(text);
        return view;
    }

}

使用newInstance方法创造对象,类似建造者模式,可以构造出不同的对象,给对象中塞入参数。

3.2 ViewPager适配器

HomeFragmentPagerAdapter.java:

package com.meituan.huangdanyang.practise;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

public class HomeFragmentPagerAdapter extends FragmentPagerAdapter {
    private int[] tabViewId = {R.drawable.selector_home_tab, R.drawable.selector_surround_tab,
            R.drawable.selector_find_tab, R.drawable.selector_order_tab, R.drawable
            .selector_my_tab};
    private String[] tabName = {"首页", "附近", "发现", "订单", "我的"};
    private Context context;

    public HomeFragmentPagerAdapter(FragmentManager fm,Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        HomeFragment homeFragment = HomeFragment.newInstance(tabName[position]);
        homeFragment.TAG = tabName[position];
        return homeFragment;
    }

    @Override
    public int getCount() {
        return Math.min(tabViewId.length,tabName.length);
    }

    public View getTabView(int pos) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item,null);
        TextView textView = view.findViewById(R.id.tab_text);
        textView.setText(tabName[pos]);
        ImageButton imageButton = view.findViewById(R.id.tab_btn);
        imageButton.setBackground(context.getDrawable(tabViewId[pos]));
        return view;
    }
}

3.3 MainActivity.java

package com.meituan.huangdanyang.practise;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import com.meituan.huangdanyang.practise.BaseActivity;

import java.util.List;

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CustomViewPager viewPager = findViewById(R.id.view_pager);
        TabLayout tabLayout = findViewById(R.id.menu);
        HomeFragmentPagerAdapter adapter = new HomeFragmentPagerAdapter(getSupportFragmentManager(),
                this);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        for (int i = 0;i < tabLayout.getTabCount();i++){
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                //设置标签应当对应的view
                tab.setCustomView(adapter.getTabView(i));
            }
        }
    }

    @Override
    protected String getName() {
        return "MainActivity";
    }

}

3.4 禁止横向滑动

写一个CustomViewPager继承自ViewPager类,在布局中使用。

package com.meituan.huangdanyang.practise;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class CustomViewPager extends ViewPager {
    private boolean canScroll = false;

    public CustomViewPager(@NonNull Context context) {
        super(context);
    }

    public CustomViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return canScroll && super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return canScroll && super.onTouchEvent(ev);
    }
}

CustomViewPager中重写了ViewPager的的事件拦截和触摸事件的方法,不能scroll时,事件拦截器和触摸事件直接返回false,不会调用原本的事件拦截和触摸事件中的实现,返回false意味着这个事件没有分发完毕,还会继续向下分发。

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

推荐阅读更多精彩内容