Android 开发之 TabLayout + ViewPager 的使用

前言

TabLayout提供了一个水平的布局用来展示Tabs,很多应用都有这样的设计,典型的有网易新闻,直播吧,知乎等。TabLayout就可以很好的完成这一职责,当然也或许各家应用的实现方式不尽相同,这里介绍下TabLayout的用法。

首先TabLayout一般都是配合Viewpager使用的,Viewpager里的Fragment随着顶部的Tab一起联动,这种场景再熟悉不过了。在没有TabLayout的日子里关于这种设计一般都是自己实现的。

效果图

Android 开发之 TabLayout + ViewPager 的使用_第1张图片

添加依赖

在 app 文件夹下的 build.gradle 文件中添加:

compile 'com.android.support:design:25.0.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.zhy:base-rvadapter:3.0.3'

布局文件

activity_text_tab.xml

"1.0" encoding="utf-8"?>
"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"
    android:orientation="vertical">

    .support.design.widget.TabLayout
        android:id="@+id/toolbar_tab"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        android:background="#fff"
        android:fillViewport="false"
        app:tabMode="fixed"
        app:layout_scrollFlags="scroll"
        app:tabIndicatorColor="#31A0FE"
        app:tabIndicatorHeight="2.0dp"
        app:tabSelectedTextColor="#31A0FE"
        app:tabTextColor="#333333">
        .support.design.widget.TabItem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="首页" />

        .support.design.widget.TabItem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="分类" />

        .support.design.widget.TabItem
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="设置" />
    .support.design.widget.TabLayout>

    .support.v4.view.ViewPager
        android:id="@+id/text_view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


list_layout.xml

"1.0" encoding="utf-8"?>
.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    .support.v7.widget.RecyclerView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

.support.v4.widget.SwipeRefreshLayout>

基本属性

app:tabMode="scrollable"   //显示模式:可滑动
app:tabMode="fixed"        //显示模式:固定

app:tabIndicatorHeight="10dp"   //指示器高度
app:tabIndicatorColor="@color/colorPrimary" // 指示器颜色

app:tabSelectedTextColor="#ffffff"  // 选择的Tab的文字颜色
app:tabTextColor="#000000"  // 未选择的Tab文字颜色
app:tabTextAppearance="@style/Base.TextAppearance.AppCompat.Large" // 文字样式

android:background="@color/colorAccent" // 背景
app:tabBackground="@color/colorPrimary" //背景

app:tabPaddingStart="10dp"
app:tabPaddingBottom="10dp"
app:tabPadding="10dp"
app:tabPaddingEnd="10dp"
app:tabPaddingTop="10dp"

app:tabGravity="center"  //居中显示
app:tabGravity="fill"    //填充

app:tabMaxWidth="50dp"   //最大宽度
app:tabMinWidth="100dp"  //最小宽度

代码

TextTabActivity.java

package com.gyq.tablayout;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import com.gyq.tablayout.fragment.ListFragment;

public class TextTabActivity extends AppCompatActivity {
    private ViewPager mViewPager;
    private ListFragment mFragment1;
    private ListFragment mFragment2;
    private ListFragment mFragment3;

    private MyPagerAdapter mPagerAdapter;

    private TabLayout mTab;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_tab);

        initView(savedInstanceState);
    }

    private void initView(Bundle savedInstanceState) {
        mViewPager = (ViewPager)findViewById(R.id.text_view_pager);
        mViewPager.setOffscreenPageLimit(2);

        mTab = (TabLayout)findViewById(R.id.toolbar_tab);

        if (savedInstanceState == null) {
            mFragment1 = new ListFragment();
            mFragment1.initData('a','z');
            mFragment2 = new ListFragment();
            mFragment2.initData('A','Z');
            mFragment3 = new ListFragment();
            mFragment3.initData('c','x');
        }

        mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTab));

        mTab.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

    }

    public class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }



        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return mFragment1;
            } else if (position == 1) {
                return mFragment2;
            }else if (position == 2) {
                return mFragment3;
            }

            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

    }
}

BaseFragment.java

package com.gyq.tablayout.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

/**
 * Created by gyq on 2017/7/5 09:11
 */
public abstract class BaseFragment extends Fragment {
    //Fragment是否已经绑定
    protected boolean isViewInitiated;

    //用户是否可见
    protected boolean isVisibleToUser;

    //是否绑定数据
    protected boolean isDataInitiated;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        isViewInitiated = true;

        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    public abstract void fetchData();

    //准备数据
    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    public boolean prepareFetchData(boolean forceUpdate) {
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            fetchData();
            isDataInitiated = true;

            return true;
        }

        return false;
    }

}

ListFragment.java

package com.gyq.tablayout.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyq.tablayout.R;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

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

/**
 * Created by gyq on 2017/7/5 09:23
 */
public class ListFragment extends BaseFragment {
    private List mDatas;
    private CommonAdapter mAdapter;
    private View view;
    private RecyclerView mListView;

    private SwipeRefreshLayout mRefresh;
    private Context mContext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getActivity();

    }

    @Override
    public void fetchData() {

    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.list_layout,container,false);
        initView();
        return view;
    }

    public void initData(char a, char b) {
        mDatas = new ArrayList<>();

        for (int i = a;i < b;i++) {
            mDatas.add("" + (char)i);
        }
    }

    private void initView() {
        mRefresh = (SwipeRefreshLayout)view.findViewById(R.id.swipeLayout);
        mListView = (RecyclerView)view.findViewById(R.id.list_view);

        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mListView.setLayoutManager(manager);

        mAdapter = new CommonAdapter(mContext,R.layout.item_text,mDatas) {
            @Override
            protected void convert(ViewHolder holder, String s, int position) {
                holder.setText(R.id.tv_item_text,mDatas.get(position));
            }
        };

        mListView.setAdapter(mAdapter);

        mRefresh.setColorSchemeResources(R.color.holo_blue_bright,
                R.color.holo_green_bright,
                R.color.holo_orange_bright,
                R.color.holo_red_bright);

        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefresh.setRefreshing(false);
            }
        });

    }
}

你可能感兴趣的:(Android,基础)