底部导航BottomTabLayout

虽然已经有了官方的BottomNavigationView,但感觉用不惯,以我对其浅薄的了解(仅仅是在demo中用了下,没为深入源码),觉得BottomNavigationView不够灵活,主要有一下几个原因:

  • 不能添加自己写的view作为BottomNavigationView 的item,因为是时候有这样的UI(简书这种还是很常见的)
QQ截图20170516132031.png
  • BottomNavigationView 的item不能超过五个,三个以上会有夸张的动画(动画可以用反射关闭,之前看过,简书上就有)

  • 好像不能显示消息数量角标

device-2017-05-16.png

用法:

布局:
    <com.nevermore.oceans.widget.BottomTabLayout
        android:id="@+id/btl"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize">
        <com.nevermore.oceans.widget.BottomTabView
            android:layout_width="0dp"
            app:tabText="首页"
            app:tabIconNormal="@mipmap/ic_launcher_round"
            app:tabIconSelected="@mipmap/ic_launcher"
            app:tabTextColorNormal="#999999"
            app:tabTextColorSelected="#2c8bef"
            android:layout_weight="1"
            android:layout_height="match_parent"/>
        <com.nevermore.oceans.widget.BottomTabView
            android:layout_width="0dp"
            android:layout_weight="1"
            app:tabIconNormal="@mipmap/ic_launcher_round"
            app:tabIconSelected="@mipmap/ic_launcher"
            app:tabTextColorNormal="#999999"
            app:tabTextColorSelected="#2c8bef"
            app:tabText="购物车"
            android:layout_height="match_parent"/>
        <com.nevermore.oceans.widget.BottomTabView
            app:tabText="我的"
            android:layout_width="0dp"
            app:tabIconNormal="@mipmap/ic_launcher_round"
            app:tabIconSelected="@mipmap/ic_launcher"
            app:tabTextColorNormal="#999999"
            app:tabTextColorSelected="#2c8bef"
            android:layout_weight="1"
            android:layout_height="match_parent"/>

    </com.nevermore.oceans.widget.BottomTabLayout>
代码1:
public class MainActivity extends AppCompatActivity {

    private TextView tv;
    private BottomTabLayout btl;

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


        btl = (BottomTabLayout) findViewById(R.id.btl);
        tv = (TextView) findViewById(R.id.tv);

        //底部每个标签的点击事件
        btl.setOnItemTabClickListener(new BottomTabLayout.OnItemTabClickListener() {
            @Override
            public void onItemTabClick(int position, View itemView) {


                if(itemView instanceof BottomTabView){
                    String tabText = ((BottomTabView) itemView).getTabText();
                    tv.setText(tabText);
                }
                //设为被选中
                btl.selectItem(itemView);

            }
        });
        
        //默认选中第一个tab
        btl.selectItem(0);
    }
}

BottomTabView:


/**
 *
 * author XuNeverMore
 * create on 2017/5/16 0016
 * github https://github.com/XuNeverMore
 */

public class BottomTabView extends FrameLayout {
    private static final String TAG = "BottomTabView";
    private Drawable drawableN;
    private Drawable drawableS;
    private ImageView tabIcon;
    private TextView tabText;
    private String text;
    private TextView tvCount;
    private int textColorNoraml = 0xff000000;
    private int textColorSelected = 0xff4caf65;

    public BottomTabView(@NonNull Context context) {
        this(context, null);
    }

    public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomTabView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //统一定制每个tab的布局,以便修改
        LayoutInflater.from(context).inflate(R.layout.item_bottom, this, true);

        //图标
        tabIcon = (ImageView) findViewById(R.id.tab_icon);
        //文字
        tabText = (TextView) findViewById(R.id.tab_text);
        //显示消息数
        tvCount = (TextView) findViewById(R.id.tv_count);

        //自定义一些属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BottomTabView);
        
        drawableN = typedArray.getDrawable(R.styleable.BottomTabView_tabIconNormal);//正常状态图标
        drawableS = typedArray.getDrawable(R.styleable.BottomTabView_tabIconSelected);//选中状态图标
        textColorNoraml = typedArray.getColor(R.styleable.BottomTabView_tabTextColorNormal, textColorNoraml);//正常文字颜色
        textColorSelected = typedArray.getColor(R.styleable.BottomTabView_tabTextColorSelected, textColorSelected);//选中状态文字颜色

        text = typedArray.getString(R.styleable.BottomTabView_tabText);

        
        //默认都显示未选中状态的图标
        if (drawableN != null) {
            tabIcon.setImageDrawable(drawableN);
        }
        
        if (!TextUtils.isEmpty(text)) {
            tabText.setText(text);
            tabText.setTextColor(textColorNoraml);
        }

        typedArray.recycle();
    }


    /**
     * 切换 tab 选中状态
     * @param select
     */
    public void setSelectState(boolean select){
        
        setSelected(select);
        tabIcon.setImageDrawable(select?drawableS:drawableN);
        tabText.setTextColor(select?textColorSelected:textColorNoraml);

    }

    /**
     * 获取 tab 上的文字
     * @return
     */
    public String getTabText(){

        return tabText.getText().toString().trim();
    }

    public void setTabText(String text){
        tabText.setText(text);
    }


    /**
     * 设置未读消息数量
     * @param count
     */
    public void setCount(int count){
        tvCount.setVisibility(count>0?VISIBLE:GONE);
        tvCount.setText(""+count);
    }

}

BottomTabView 就是封装了一个布局:

R.layout.item_bottom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   <ImageView
       android:id="@+id/tab_icon"
       android:scaleType="center"
       android:layout_marginTop="8dp"
       android:layout_centerHorizontal="true"
       android:duplicateParentState="true"
       android:layout_width="24dp"
       android:layout_height="24dp" />
    <TextView
        android:id="@+id/tab_text"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="5dp"
        android:text="folder"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:visibility="gone"
        android:id="@+id/tv_count"
        android:layout_toRightOf="@+id/tab_icon"
        android:text="5"
        android:layout_marginTop="2dp"
        android:layout_marginLeft="-12dp"
        android:textColor="#ffffff"
        android:background="@drawable/rect_round_red"
        android:textSize="12sp"
        android:gravity="center"
        android:paddingLeft="6dp"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:paddingRight="6dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</RelativeLayout>
QQ截图20170516125040.png

这个item 布局可以根据需求自己修改,消息数量默认是gone,可以通过以下方法显示:

public void setCount(int count){
        tvCount.setVisibility(count>0?VISIBLE:GONE);
        tvCount.setText(""+count);
    }

几个自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="BottomTabView">
        <attr name="tabIconNormal" format="reference"/>
        <attr name="tabIconSelected" format="reference"/>
        <attr name="tabTextColorNormal" format="color"/>
        <attr name="tabTextColorSelected" format="color"/>
        <attr name="tabText" format="string"/>

    </declare-styleable>
</resources>

BottomTabLayout :

继承LinearLayout,用来管理每个tab的点击、选中,当然tab并不一定是BottomTabView类型的,
可以是自己写的View

/**
 *
 * author XuNeverMore
 * create on 2017/5/16 0016
 * github https://github.com/XuNeverMore
 */

public class BottomTabLayout extends LinearLayout {
    public BottomTabLayout(Context context) {
        this(context, null);
    }

    public BottomTabLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomTabLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOrientation(HORIZONTAL);//水平方向

    }

    private static final String TAG = "BottomTabLayout";
    private View lastSelectedItemView;//上一个被选中的item


    /**
     * 每个tab 点击事件 类似ListView的OnItemClickListener
     */
    public interface OnItemTabClickListener {

        void onItemTabClick(int position, View itemView);
    }
    private OnItemTabClickListener onItemTabClickListener;

    public void setOnItemTabClickListener(OnItemTabClickListener onItemTabClickListener) {
        this.onItemTabClickListener = onItemTabClickListener;
        setListeners();
    }

    
    
    
    
    
    /**
     * 为每个tab 设置点击事件
     */
    private void setListeners() {
        int childCount = getChildCount();
        Log.i(TAG, "setListeners: "+childCount);

        //为BottmoTabLayout 的每个childView设置点击事件 
        for (int i = 0; i < childCount; i++) {

            final int position = i;

            final View child = getChildAt(i);
            child.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemTabClickListener != null) {

                        //防止选中的tab被重复点击
                        if(lastSelectedItemView!=null&&lastSelectedItemView==v){
                            
                            return;
                        }
                        onItemTabClickListener.onItemTabClick(position, v);
                    }
                }
            });
        }
    }
    

    //选中一个tab 并改变其状态
    public void selectItem(View itemView){

        //让上一个被选中的tab恢复原来状态
        if(lastSelectedItemView!=null){
            changeItemSelectState(lastSelectedItemView,false);
        }
        //选中itemView
        changeItemSelectState(itemView,true);
        //保存itemView 下次切换修改
        lastSelectedItemView = itemView;
    }


    public void selectItem(int position){
        if(position<getChildCount()){
            View childAt = getChildAt(position);
            selectItem(childAt);
        }
    }


    //改变tab 选中状态
    private void changeItemSelectState(View view,boolean selected){

        if(view instanceof BottomTabView){//如果是tab 是BottomTabView类型的单独设置
            ((BottomTabView) view).setSelectState(selected);
        }else {
            view.setSelected(selected);
        }

    }
    
}

主要用法就是代码1

//底部每个标签的点击事件
        btl.setOnItemTabClickListener(new BottomTabLayout.OnItemTabClickListener() {
            @Override
            public void onItemTabClick(int position, View itemView) {


                if(itemView instanceof BottomTabView){
                    String tabText = ((BottomTabView) itemView).getTabText();
                    tv.setText(tabText);
                }
                //设为被选中
                btl.selectItem(itemView);

            }
        });

因为现在做的项目,要判断登录状态,在未登录状态下,点击要调到登录页面,所以没有象TabLayout那样写一个setUpWithViewPager(viewpager);方法,直接在OnItemTabClickListener里切换就可以了,这样更灵活点。

虽然更灵活了,但是要多写一句btl.selectItem(itemView); 将你点击的tab设为选中状态

github 源码

gs.png

第一次完全用Markdown写东西,瞬间觉得学了一门语言。

End

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,106评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,408评论 0 17
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,757评论 22 665
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,102评论 4 62
  • 不落雪的原因很多 比如 春天太近 冬天太远 不想家的原因很多 比如 北方太近 南方太远 不主动的原因很多 比如 离...
    故墙阅读 208评论 7 4