安卓UI我的面试准备

TabLayout自定义tab,实现多样导航栏

2019-01-07  本文已影响166人  奔跑的佩恩

前言

之前讲过TabLayout的基本属性全解,但是对于TabLayout实现的导航栏仍是有诸多限制,例如不能任意设置text的文字大小,若导航中涉及到图片的话,图片只能简单的设计到文字上方,所以布局方面仍是很受限制,为了解决这种情况,这篇文章就介绍TabLayout自定义tab,让你导航栏随心所欲的布局。

此篇文章将介绍以下内容:

  1. TabLayout库的导入
  2. TabLayout自定义导航的实现
  3. 需要注意的地方
  4. 效果图
一.TabLayout库的导入

TabLayout属于android的Design库中的控件,所以需要在使用之前在项目的app对应的buildle.gradle中导入该库

    //TabLayout
    implementation 'com.android.support:design:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
二.TabLayout自定义导航的实现
2.1 mainActivity对应的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="com.android.testdemo.main.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="0dp"
        android:layout_height="@dimen/dp_80"
        app:tabMode="scrollable"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tablayout" />
</android.support.constraint.ConstraintLayout>
2.2 需要加载的Fragment的代码

TabLayout和ViewPager实现的导航栏,肯定涉及到Fragment了,下面给出MyFragment.java代码:

public class MyFragment extends AppFragment {

    @BindView(R.id.tv_name)
    TextView mTvName;

    private String mName;

    @Override
    public void onCreate(@Nullable Bundle bundle) {
        super.onCreate(bundle);
        if(getArguments()!=null){
            mName = getArguments().getString("text");
        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_my;
    }

    @Override
    public void initData() {
        mTvName.setText(mName);
    }

    @Override
    public void setListener() {

    }

    @Override
    protected void onVisible(boolean isFirstTimeLoad) {

    }

    @Override
    protected void onInvisible() {

    }
}
2.3 MyFragment对应的fragment_my.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="com.android.testdemo.main.MainActivity">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
2.4 ViewPager对应的adapter,即TabFragmentAdapter代码
package com.android.testdemo.function;

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.TextView;

import com.android.testdemo.R;

import java.util.List;

/**
 * Title:
 * Description:
 * <p>
 * Created by pei
 * Date: 2018/12/12
 */
public class TabFragmentAdapter extends FragmentPagerAdapter {

    private String[] mTitles;
    private Context mContext;
    private List<Fragment> mFragments;

    public TabFragmentAdapter(List<Fragment> fragments, String[] titles, FragmentManager fm, Context context) {
        super(fm);
        this.mContext = context;
        this.mFragments = fragments;
        this.mTitles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }

    public View getTabView(int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_header, null);
        TextView textView=view.findViewById(R.id.tv_header);
        textView.setText(mTitles[position]);
        return view;
    }
}

当中getTabView(int position)即为自定义Tab的布局,这在mainActivity中会用到,这里给出自定义布局item_header.xml的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="horizontal"
    tools:context="com.android.testdemo.main.MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@mipmap/ic_launcher"/>

    <TextView
        android:id="@+id/tv_header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/dp_5"
        android:textColor="@color/blue"
        android:textSize="@dimen/sp_12"
        android:gravity="center"/>
</LinearLayout>
2.5 MainActivity中的代码
package com.android.testdemo.main;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.android.testdemo.R;
import com.android.testdemo.base.BaseActivity;
import com.android.testdemo.function.TabFragmentAdapter;
import com.android.testdemo.utils.LogUtil;
import com.android.testdemo.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MainActivity extends BaseActivity{

    @BindView(R.id.tablayout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    private String mTitles[] = {
            "上海", "头条推荐", "生活", "娱乐八卦", "体育",
            "段子", "美食", "电影", "科技", "搞笑",
            "社会", "财经", "时尚", "汽车", "军事",
            "小说", "育儿", "职场", "萌宠", "游戏",
            "健康", "动漫", "互联网"};

    private List<Fragment> mFragments;
    private TabFragmentAdapter mTabFragmentAdapter;

    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        mFragments = new ArrayList<>();

        for (int i = 0; i < mTitles.length; i++) {
            Fragment fragment = new MyFragment();
            Bundle bundle = new Bundle();
            bundle.putString("text", mTitles[i]);
            fragment.setArguments(bundle);
            mFragments.add(fragment);
        }

        mTabFragmentAdapter = new TabFragmentAdapter(mFragments, mTitles, getSupportFragmentManager(), mContext);
//        mViewPager.setOffscreenPageLimit(mFragments.size());// 设置预加载Fragment个数
        mViewPager.setOffscreenPageLimit(6);// 设置预加载Fragment个数
        mViewPager.setAdapter(mTabFragmentAdapter);
        mViewPager.setCurrentItem(0);// 设置当前显示标签页为第一页

        // 将ViewPager和TabLayout绑定
        mTabLayout.setupWithViewPager(mViewPager);
        //设置自定义tab
        for (int i = 0; i < mTabLayout.getTabCount(); i++){
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(mTabFragmentAdapter.getTabView(i));
            }
        }
        //设置第一页为选中状态时的tab文字颜色为红色
        View view=mTabLayout.getTabAt(0).getCustomView();
        TextView textView=view.findViewById(R.id.tv_header);
        textView.setTextColor(Color.RED);

    }

    @Override
    public void setListener() {
        //监听事件
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //选中了tab的逻辑
                LogUtil.i("======我选中了====");

                View view=tab.getCustomView();
                TextView textView=view.findViewById(R.id.tv_header);
                textView.setTextColor(Color.RED);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //未选中tab的逻辑
                LogUtil.i("======我未被选中====");

                View view=tab.getCustomView();
                TextView textView=view.findViewById(R.id.tv_header);
                textView.setTextColor(Color.BLUE);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次选中tab的逻辑
                LogUtil.i("======我再次被选中====");
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

    }


    private void showShort(String msg){
        ToastUtil.shortShow(mContext,msg);
    }
}
三. 需要注意的地方
  1. 可以在item_header.xml中自定义你想要的布局
  2. 在MainActivity中,"设置自定义tab"的代码必须在"将ViewPager和TabLayout绑定"的代码之后执行,不然自定义布局不起效果
  3. mainActivity对应的xml中TabLayout控件的高度必须用一个固定值,不能用wrap_content,不然会不起效果
mViewPager.setCurrentItem(0);// 设置当前显示标签页为第一页  

设置的初始项要和

        //设置第一页为选中状态时的tab文字颜色为红色
        View view=mTabLayout.getTabAt(0).getCustomView();
        TextView textView=view.findViewById(R.id.tv_header);
        textView.setTextColor(Color.RED);

设置的初始项保持一致

  1. 在 mTabLayout.addOnTabSelectedListener方法中要记得设置导航文字的选中和未选中文字颜色,当然在item_header.xml中要给text设置一个初始textcolor。
四.效果图
效果图.gif

ok,今天的内容就到这里了。

上一篇下一篇

猜你喜欢

热点阅读