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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 导航条效果实现 TabLayout+ViewPager+Fragment相关的知识,希望对你有一定的参考价值。

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"));

效果:
技术分享



  • 你需要通过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>

效果如下:
技术分享






ViewPager+TabLayout实现导航效果

目标效果一:

技术分享

方法一:

如果你将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>






目标效果二

技术分享
实现方法:

//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默认可以实现图示的效果的,比较简单,这里讲述,如何自定义效果。
可以自定义每个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>

图片资源:
技术分享技术分享技术分享技术分享技术分享技术分享技术分享技术分享技术分享技术分享








注意

  • 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


























































以上是关于Android 导航条效果实现 TabLayout+ViewPager+Fragment的主要内容,如果未能解决你的问题,请参考以下文章

Android 修改TabLayout底部导航条Indicator的长短

TabLayout实现顶部导航

Android原生TabLayout使用全解析,看这篇就够了

Android原生TabLayout使用全解析,看这篇就够了

Android - MD之TabLayout的使用

Android 滑动定位+吸附悬停效果实现