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

http://blog.csdn.net/qq_33425116/article/details/52599818

时间: 2024-10-12 19:36:13

Android 导航条效果实现(六) TabLayout+ViewPager+Fragment的相关文章

Android开发之漫漫长途 Fragment番外篇——TabLayout+ViewPager+Fragment

该文章是一个系列文章,是本人在Android开发的漫漫长途上的一点感想和记录,我会尽量按照先易后难的顺序进行编写该系列.该系列引用了<Android开发艺术探索>以及<深入理解Android 卷Ⅰ,Ⅱ,Ⅲ>中的相关知识,另外也借鉴了其他的优质博客,在此向各位大神表示感谢,膜拜!!! 前言 上一篇文章中我们使用底部导航+Fragment的方式实现了Android主流App中大都存在的设计.并命名其为"Fragment最佳实践",作为想到单独使用Fragment的用

导航条效果

<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-widt

三角形变形记之纯css实现的分布导航条效果

三角形变形记,用纯css实现的分布导航条效果 <style type="text/css"> ul,li { list-style-type:none; font-size:13px; font-weight:bold; } li { float:left; position:relative; line-height:30px; background:#9BBB38; color:#fff; width:100px; height:30px; text-align:cen

JS实现导航条效果——current跟随鼠标hover移动

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-

Android滑动导航菜单TabLayout+ViewPager+Fragment

1.主要的Activity--MemberDetailActivity 2.Activity视图的xml文件--R.layout.activity_member_detail 3.自定义的Fragment子类--CustomTrainingFragment 4.Fragment视图的xml文件-- 5.自定义Fragment子类的适配器 //1.MemberDetailActivitypackage com.vimems.coach; import android.os.Bundle; impo

032实现导航条效果

效果如下: ViewController.h 1 #import <UIKit/UIKit.h> 2 3 @interface ViewController : UIViewController 4 @end ViewController.m 1 #import "ViewController.h" 2 3 @interface ViewController () 4 - (void)layoutUI; 5 @end 6 7 @implementation ViewCont

DIV+CSS实现仿京东商城导航条效果

1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 3 <html xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta http-equiv=&quo

关于tablayout+viewpager+fragment配合使用的一点记录

最近在写项目的时候遇到要求使用tablayout和fragment,遇到了这里记录一下大致思路. tablayout是头部可以左右切换的头部控制栏控件,配合viewpager使用,fragment是碎片,可以放在viewpager里面,实现类似网易云音乐首页切换的效果.效果图如下: 首先添在build.gradle里面添加依赖: 1 implementation 'com.android.support:support-v4:28.0.0' 2 implementation 'com.andro

TabLayout+ViewPager+Fragment 快速实现标题切换效果

首先呢,这个控件使用起来并不难,算是非常简单的了,不过这个 TabLayout 的 setupWithViewPager 方法有坑,要注意了,具体什么坑,自己踩过才有映像,我这里就不说了,就介绍一下如何使用吧. 在 FragmentOne 中的布局文件里面添加一个 ViewPager 和一个 TabLayout,代码如下: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:and