TabLayout輕松實現仿今日頭條頂部tab導航效果


前言

 自android5.0出來后,谷歌使用了Material Design設計風格,隨着帶來了許多新的控件,如:SnackBar,TextinputLayout,以及今天使用的TabLayout,這些新控件的出現使得我們這些開發者更加方便,下面我們用TabLayout實現仿最新版的今日頭條頂部導航的效果。
這是我們今天要實現的一個效果:

這里寫圖片描述

大家看到這個效果,你會怎么實現它?在以前,我們可以通過以下幾種啊方式來實現:

  1. ViewPagerIndicator + Fragment + ViewPager
  2. ActionBar + Fragment + ViewPager
  3. 自定義一個View實現上面的效果

 ViewPagerIndicator是一個國外大牛寫的一個github開源控件,使用也很簡單,但是得設置Activity的主題,這樣難免有所耦合,而ActionBar實現簡單,但耦合性也高,如果我們程序不使用ActionBar,那么第二種方式就沒有了,而且怎么添加右邊的更多按鈕更是一個大問題,那么今天我們使用谷歌新出的控件TabLayout來實現這一效果,可以說TabLayout實現這種效果最簡單最方便了,而且沒有耦合,獨立封裝的一個控件。

下面我們通過代碼一步一步地實現上面的導航效果:

代碼編寫

編碼代碼之前,添加程序所需要的依賴:

compile 'com.android.support:design:23.0.1'
compile 'com.android.support:support-v4:23.0.1'

第一步:編寫布局,activity_main.xml

<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:orientation="vertical"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#D33C3C"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <android.support.design.widget.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:tabIndicatorColor="@android:color/transparent"
            app:tabMode="scrollable">
        </android.support.design.widget.TabLayout>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:src="@mipmap/ic_plus"/>
    </LinearLayout>


    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></android.support.v4.view.ViewPager>
</LinearLayout>

說明:

 1、 可以看到TabLayout使用和其他控件一樣,要注意的是添加命名空間,和設置tabMode屬性為可以滾動:

app:tabMode="scrollable">

 2、 設置導航底部的指示顏色為透明,即去掉底部的矩形指示器,當然設置成其他顏色那么底部就會有相應顏色的矩形指示器

app:tabIndicatorColor="@android:color/transparent"

第二步:為ViewPager設置Adapter

ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
List<Fragment> fragments = new ArrayList<Fragment>();
for (int i = 0; i < titles.length; i++) {
    Fragment fragment = new MyFragment();
    Bundle bundle = new Bundle();
    bundle.putString("text",titles[i]);
    fragment.setArguments(bundle);
    fragments.add(fragment);
}
viewPager.setAdapter(new TabFragmentAdapter(fragments, titles, getSupportFragmentManager(), this));

MyFragment.java

package com.lt.tablayouttest;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by lt on 2015/12/14.
 */
public class MyFragment extends Fragment{

    private String mText;

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        TextView textView = new TextView(getActivity());
        ViewGroup.LayoutParams params= new ViewGroup.LayoutParams(-1,-1);
        textView.setLayoutParams(params);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.RED);
        textView.setText(mText);
        return textView;
    }
}

 說明:我們可以通過fragment.setArguments(Bundle bundle)為fragment傳遞數據,然后再fragment中通過getArguments()取出bundle中的數據。

TabFragmentAdapter.java

package com.lt.tablayouttest;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by lt on 2015/12/14.
 */
public class TabFragmentAdapter extends FragmentPagerAdapter{

    private final String[] titles;
    private Context context;
    private List<Fragment> fragments;

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


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

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

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

 說明:重寫getPageTitle(int position)返回每個頁面的導航標題,這樣TabLayout會從ViewPager中得到Adapter並通過該方法拿到標題。

第三步:將TabLayouth和ViewPager綁定

// 初始化
TabLayout tablayout = (TabLayout) findViewById(R.id.tablayout);
// 將ViewPager和TabLayout綁定
tablayout.setupWithViewPager(viewPager);
// 設置tab文本的沒有選中(第一個參數)和選中(第二個參數)的顏色
tablayout.setTabTextColors(getResources().getColor(R.color.dark_white),Color.WHITE);

總結

TabLayout實現tab導航效果比以前那些實現新聞資訊類app頂部tab導航效果更加簡單方便,技術在更新,我們在進步,更多使用方法翻牆查看官方文檔:

android開發官網:http://developer.android.com/index.html

Demo下載:http://download.csdn.net/detail/ydxlt/9354379


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM