Android 导航条效果实现(六) TabLayout+ViewPager+Fragment

原创 2016年09月20日 20:53:33

TabLayout

一、继承结构

public class TabLayout  extends HorizontalScrollView 

java.lang.Object
    ↳ android.view.View
        ↳ android.view.ViewGroup
            ↳ android.widget.FrameLayout
                ↳ android.widget.HorizontalScrollView
                    ↳ android.support.design.widget.TabLayout

二、TabLayout的使用

1、TabLayout简单使用

  • TabLayout来自design兼容包,使用需要添加依赖。android studio 添加依赖如下:
dependencies {
    ~~~
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:24.2.0'
}


  • TabLayout可以水平放置一些tab标签


  • 标签的展示通过 TabLayout.Tab的实例来实现,通过 newTab()方法可以创建这些示例,并且可以通过 setText(int)setIcon(int)方法分别设置标签的文本的图标。 另外,需要通过layout的setTab(Tab)方法把一个标签展示出来。例如:
tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));

效果:
TabLayout



  • 你需要通过setOnTabSelectedListener(OnTabSelectedListener)方法,来给标签的选择改变设定一个监听器。当选择状态改变的时候,会通知你的监听器。

  • 你在布局中也可以通过使用TabItem标签给TabLayout设置子标签,例如:

<android.support.design.widget.TabLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="标签" />

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@mipmap/ic_launcher" />
</android.support.design.widget.TabLayout>

效果如下:
TabLayout






ViewPager+TabLayout实现导航效果

目标效果一:

TabLayout+ViewPager

方法一:

如果你将TabLayout与ViewPager一起使用,你可以通过调用setupWithViewPager(ViewPager)方法来绑定绑定两个控件。TabLayout将自动出现在ViewPager的标题位置。
方法如下:
MainActivity.java

package com.noonecode.tablayoutdemo;

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 android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    private List<Fragment> list;
    private MyAdapter adapter;
    private String[] titles = {"页面1", "页面2", "页面3"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        //页面,数据源
        list = new ArrayList<>();
        list.add(new Tab1Fragment());
        list.add(new Tab2Fragment());
        list.add(new Tab3Fragment());
        //ViewPager的适配器
        adapter = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        //绑定
        tabLayout.setupWithViewPager(viewPager);
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }

        //重写这个方法,将设置每个Tab的标题
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}

activity_main.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.noonecode.tablayoutdemo.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <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>



方法二:

TabLayout也支持当作ViewPager的装饰来使用,通过在布局中直接把它添加到ViewPager的内部(将自动将ViewPager的标题作为TabLayout的Tab)
如下方式使用:
MainActivity.java

package com.noonecode.tablayoutdemo;

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 android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;

    private List<Fragment> list;
    private MyAdapter adapter;
    private String[] titles = {"页面1", "页面2", "页面3"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        //页面,数据源
        list = new ArrayList<>();
        list.add(new Tab1Fragment());
        list.add(new Tab2Fragment());
        list.add(new Tab3Fragment());
        //ViewPager的适配器
        adapter = new MyAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
    }

    class MyAdapter extends FragmentPagerAdapter {

        ...

        //重写这个方法,将设置每个Tab的标题
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}

activity_main.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.noonecode.tablayoutdemo.MainActivity">


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

        <android.support.design.widget.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        </android.support.v4.view.ViewPager>
</LinearLayout>






目标效果二

TabLayout+ViewPager
实现方法:

//MODE_SCROLLABLE可滑动的展示
//MODE_FIXED固定展示
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

其他可定制属性:

XML attributes
android.support.design:tabBackground Reference to a background to be applied to tabs.
android.support.design:tabContentStart Position in the Y axis from the starting edge that tabs should be positioned from.
android.support.design:tabGravity Gravity constant for tabs.
android.support.design:tabIndicatorColor Color of the indicator used to show the currently selected tab.
android.support.design:tabIndicatorHeight Height of the indicator used to show the currently selected tab.
android.support.design:tabMaxWidth The maximum width for tabs.
android.support.design:tabMinWidth The minimum width for tabs.
android.support.design:tabMode The behavior mode for the Tabs in this layout
Must be one of the following constant values.
android.support.design:tabPadding The preferred padding along all edges of tabs.
android.support.design:tabPaddingBottom The preferred padding along the bottom edge of tabs.
android.support.design:tabPaddingEnd The preferred padding along the end edge of tabs.
android.support.design:tabPaddingStart The preferred padding along the start edge of tabs.
android.support.design:tabPaddingTop The preferred padding along the top edge of tabs.
android.support.design:tabSelectedTextColor The text color to be applied to the currently selected tab.
android.support.design:tabTextAppearance A reference to a TextAppearance style to be applied to tabs.
android.support.design:tabTextColor The default text color to be applied to tabs.


Constants
int GRAVITY_CENTER Gravity used to lay out the tabs in the center of the TabLayout.
int GRAVITY_FILL Gravity used to fill the TabLayout as much as possible.
int MODE_FIXED Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs.
int MODE_SCROLLABLE Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels and a larger number of tabs.






目标效果三:

TabLayout+ViewPager


实现方法:
TabLayout默认可以实现图示的效果的,比较简单,这里讲述,如何自定义效果。
可以自定义每个Tab的的布局样式,实现丰富的效果。如下:
tab_custom.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:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="30dp"
        android:layout_height="30dp" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

activity_main.xml
这里需要把指示条隐藏掉:tabIndicatorHeight="0dp"

<?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:orientation="vertical"
    tools:context="com.noonecode.tablayoutdemo.MainActivity">

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

    <android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:tabSelectedTextColor="#59D"
        app:tabTextColor="#999"
        app:tabIndicatorHeight="0dp" />
</LinearLayout>

MainActivity.java

package com.noonecode.tablayoutdemo;

import android.content.Context;
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 android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    private List<Fragment> list;
    private MyAdapter adapter;
    private String[] titles = {"主页", "群组", "搜索", "消息", "更多"};
    private int images[] = {R.drawable.home_selector, R.drawable.group_selector, R.drawable.square_selector, R.drawable.message_selector, R.drawable.more_selector};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //实例化
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        //页面,数据源
        list = new ArrayList<>();
        list.add(new Tab1Fragment());
        list.add(new Tab2Fragment());
        list.add(new Tab3Fragment());
        list.add(new Tab4Fragment());
        list.add(new Tab5Fragment());
        //ViewPager的适配器
        adapter = new MyAdapter(getSupportFragmentManager(), this);
        viewPager.setAdapter(adapter);
        //绑定
        tabLayout.setupWithViewPager(viewPager);
        //设置自定义视图
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(adapter.getTabView(i));
        }
    }

    class MyAdapter extends FragmentPagerAdapter {

        private Context context;

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

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

        @Override
        public int getCount() {
            return list.size();
        }

        /**
         * 自定义方法,提供自定义Tab
         *
         * @param position 位置
         * @return 返回Tab的View
         */
        public View getTabView(int position) {
            View v = LayoutInflater.from(context).inflate(R.layout.tab_custom, null);
            TextView textView = (TextView) v.findViewById(R.id.tv_title);
            ImageView imageView = (ImageView) v.findViewById(R.id.iv_icon);
            textView.setText(titles[position]);
            imageView.setImageResource(images[position]);
            //添加一行,设置颜色
            textView.setTextColor(tabLayout.getTabTextColors());//
            return v;
        }
    }
}

一些资源:
home_selector.xml,其他的类似

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

图片资源:
homenormalhomeselectedmsgnormalmsgselectedgroupnormalgroupselectedsearchnormalsearchselectedmorenormalmorepressed








注意

  • TabLayout是5.0出来后的design兼容包内的,如要使用,请手动添加依赖。
  • 本例使用Android Studio导包只需要添加添加依赖,将自动下载项目。
  • 绑定ViewPager之后,将自动将ViewPager的标题作为Tab标签,需要重写适配器的getPageTitle方法给其设置标题。这时,通过addTab添加的Tab将是无效的。
  • AppCompatActivity继承自FragmentActivity,小伙伴们继承自FragmentActivity也是一样使用的。
  • 如有问题请留言。




(完毕)

导航:
Android 导航条效果实现(一) TabActivity+TabHost
http://blog.csdn.net/qq_33425116/article/details/52573967

Android 导航条效果实现(二) FragmentTabHost
http://blog.csdn.net/qq_33425116/article/details/52575811

Android 导航条效果实现(三) ViewPager+PagerTabStrip
http://blog.csdn.net/qq_33425116/article/details/52577570

Android 导航条效果实现(四) ViewPager+自定义导航条
http://blog.csdn.net/qq_33425116/article/details/52584282

Android 导航条效果实现(五) ActionBar+Fragment
http://blog.csdn.net/qq_33425116/article/details/52587635

Android 导航条效果实现(六) TabLayout+ViewPager+Fragment
http://blog.csdn.net/qq_33425116/article/details/52599818

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33425116/article/details/52599818

ViewPager+Tablayout的联动效果

快速集成的Tablayout+ViewPager 实现联动效果
  • GHQZWW
  • GHQZWW
  • 2017-08-18 21:30:42
  • 3847

TabLayout配合viewpager的简单使用

TabLayout配合viewpager的简单使用这几天在网上搜了一下tabLayout的使用,因为之前在应用viewpager的时候,经常会使用TabPageIndicator来与其配合。达到很漂亮...
  • qq_31927865
  • qq_31927865
  • 2016-08-17 11:15:10
  • 2917

TabLayout结合ViewPager使用

Java代码: /** * Created by wzl on 2016/4/15. * 分享 */ public class SharesActivity extends AppCompatA...
  • m190607070
  • m190607070
  • 2016-07-07 16:15:03
  • 2155

TabLayout+ViewPager简易实现

//在gradle中配置依赖compile 'com.android.support:design:25.3.1' //布局文件 //activity_main布局     an...
  • ZhouZhouSunShine
  • ZhouZhouSunShine
  • 2017-08-18 20:40:04
  • 605

用TabLayout实现选项卡滑动效果

实际开发中,ViewPager经常结合Fragment来使用,然后再使用三方开源的PagerSlidingTabStrip去实现类似选项卡滑动效果。我之前那个APP的首页就是这样搭建的。 基于Mat...
  • tyk0910
  • tyk0910
  • 2016-05-13 14:57:31
  • 19935

android 开发 TabLayout+ViewPager 点击+滑动效果

TabLayout是android design包内的控件;  一般情况下,它总是喜欢和ViewPager成对出现; 实现效果图: 具体代码实现如下: ...
  • u012607014
  • u012607014
  • 2017-02-09 15:18:07
  • 745

标签栏TabLayout与ViewPager的那些事

一,引言上图是简书Android端的主页Tab,在其他的App中Tab也是很常见的,它的实现方式也有很多:TabHost,自定义控件(第三方库),RadioGroup等等。这里主要介绍Android ...
  • monkey646812329
  • monkey646812329
  • 2017-05-26 16:54:53
  • 366

ViewPager实现页卡的最新方法--简洁的TabLayout(谷歌支持包)

效果图:添加依赖包: compile 'com.android.support:design:22.2.0'布局文件:
  • pengkv
  • pengkv
  • 2015-07-17 14:24:49
  • 28596

【Android 基础】ViewPager&TabLayout使用简例

前言: 应用viewpager的时候,一般会使用TabPageIndicator来与其配合,达到很漂亮的效果。但是TabPageIndicator是第三方的,而且比较老了,当然了现在很多大神都已经...
  • leaf_130
  • leaf_130
  • 2017-01-16 22:38:20
  • 636
收藏助手
不良信息举报
您举报文章:Android 导航条效果实现(六) TabLayout+ViewPager+Fragment
举报原因:
原因补充:

(最多只允许输入30个字)