ViewPager2+Fragment+TabLayout
ViewPager2
2019初Google正式发布了ViewPager2。只要我们已经从Suppor库切换到AndroidX,便可以使用ViewPager2完全取代旧的ViewPager。
ViewPager2最显著的特点是基于RecyclerView实现,RecyclerView是目前Android端最成熟的AdapterView解决方案,这带来诸多好处:
- 抛弃传统的PagerAdapter,统一了Adapter的API
- 通过LinearLayoutManager可以实现类似抖音的纵向滑动
- 支持DiffUitl,可以通过diff实现局部刷新
- 支持RTL(right-to-left)布局,对于一些有出海需求的APP非常有用
- 支持ItemDecorator
ViewPager2 + Fragment
跟ViewPager一样,除了View以外,ViewPager2更多的是配合Fragment的使用,这需要借助FragmentStateAdapter:
View | Adapter |
---|---|
ViewPager | FragmentStatePagerAdapter、PagerAdapter |
ViewPager2 | FragmentStateAdapter |
TabLayout
TabLayout提供了一个水平布局用于展示tabs,继承自HorizontalScrollView。
一般与Viewpager结合使用实现页面和标签联动的效果,是时下APP中非常常用的一个控件。
1、简单应用(两种方式)
(1)xml中添加tab
<android.support.design.widget.TabLayout android:id="@+id/tab_layout" 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="Tab1"/> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab2"/> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab3"/> <android.support.design.widget.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab4"/> </android.support.design.widget.TabLayout>
(2)代码中添加tab
xml文件
<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.design.widget.TabLayout>
java代码
// tablayout,Tab是TabLayout的内部类,且Tab的构造方法是包访问权限 TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("Tab1")); tabLayout.addTab(tabLayout.newTab().setText("Tab2")); tabLayout.addTab(tabLayout.newTab().setText("Tab3")); tabLayout.addTab(tabLayout.newTab().setText("Tab4"));
注意:使用<android.support.design.widget.TabLayout>和<android.support.design.widget.TabItem>需要使用android.support.design.widget这个包,所以我们需要在build.gradle中加入了相关的依赖。
implementation 'com.android.support:design:28.0.0'
2、TabLayout属性详解
<declare-styleable name="TabLayout"> <!--指示器颜色--> <attr name="tabIndicatorColor" format="color"/> <!--指示器高度--> <attr name="tabIndicatorHeight" format="dimension"/> <!--指示器宽度 true:和tab同宽 false:和tab中的字同宽 --> <attr name="tabIndicatorFullWidth" format="boolean"/> <!--tabs距TabLayout开始位置的偏移量,但app:tabMode="scrollable"才生效--> <attr name="tabContentStart" format="dimension"/> <!--仅是Tab背景,设置TabLayout背景用android:background--> <attr name="tabBackground" format="reference"/> <!--默认fixed,所有Tab只能在屏幕内显示,超出会被挤压;scrollable,tab数量多会超出屏幕,可滑动--> <attr name="tabMode"> <enum name="scrollable" value="0"/> <enum name="fixed" value="1"/> </attr> <!--默认fill,tab填满TabLayout,但tabMode=“fixed”才生效;center,tabs位于TabLayout的中间--> <attr name="tabGravity"> <enum name="fill" value="0"/> <enum name="center" value="1"/> </attr> <!--Tab的最小宽度--> <attr name="tabMinWidth" format="dimension"/> <!--Tab的最大宽度--> <attr name="tabMaxWidth" format="dimension"/> <!--Tab文本设置样式--> <attr name="tabTextAppearance" format="reference"/> <!--Tab未选中字体颜色--> <attr name="tabTextColor" format="color"/> <!--Tab选中字体颜色--> <attr name="tabSelectedTextColor" format="color"/> <!--Tab内填充相关--> <attr name="tabPaddingStart" format="dimension"/> <attr name="tabPaddingTop" format="dimension"/> <attr name="tabPaddingEnd" format="dimension"/> <attr name="tabPaddingBottom" format="dimension"/> <attr name="tabPadding" format="dimension"/> </declare-styleable>
使用示例
<android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="@color/colorPrimaryDark" app:tabIndicatorHeight="2dp" app:tabContentStart="50dp" app:tabBackground="@color/colorAccent" app:tabMode="scrollable" app:tabGravity="fill" app:tabTextAppearance="@style/MyTabTextAppearance" app:tabTextColor="@android:color/black" app:tabSelectedTextColor="@android:color/white"/>
<style name="MyTabTextAppearance" parent="TextAppearance.Design.Tab"> <item name="textAllCaps">false</item> <item name="android:textSize">18sp</item> </style>
刚才我们用的是<android.support.design.widget.TabLayout>和<android.support.design.widget.TabItem>
我们还可以使用<com.google.android.material.tabs.TabLayout>和<com.google.android.material.tabs.TabItem>
<?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=".MainActivity"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/vpMain" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tlMain" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.1" android:background="@color/blue" app:tabIndicatorColor="@color/white" app:tabIndicatorHeight="3dp" > <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab1"/> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab2"/> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab3"/> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab4"/> <com.google.android.material.tabs.TabItem android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tab5"/> </com.google.android.material.tabs.TabLayout> </LinearLayout>
注意:使用<com.google.android.material.tabs.TabLayout>和<com.google.android.material.tabs.TabItem>需要使用com.google.android.material这个包,所以我们需要在build.gradle中加入了相关的依赖。
implementation 'com.google.android.material:material:1.4.0'
实践
1、创建MainActivity
MainActivity.java
package com.sdbi.smartcityli01; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.widget.ViewPager2; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; import com.sdbi.smartcityli01.fragment.HomeFragment; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private String[] menus = {"首页", "服务", "党建", "新闻", "个人"}; private int[] menuLogos = {R.drawable.one, R.drawable.one, R.drawable.one, R.drawable.one, R.drawable.one}; private List<Fragment> fragmentList; private ViewPager2 vpMain; private TabLayout tlMain; // private TabLayout.Tab tab; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); // 初始化控件 fragmentList = new ArrayList<Fragment>(); fragmentList.add(new HomeFragment()); fragmentList.add(new HomeFragment()); fragmentList.add(new HomeFragment()); fragmentList.add(new HomeFragment()); fragmentList.add(new HomeFragment()); // 创建ViewPager2所使用的适配器,FragmentStateAdapter抽象类的实现类对象 FragmentStateAdapter adapter = new FragmentStateAdapter(MainActivity.this) { @NonNull @Override public Fragment createFragment(int position) { return fragmentList.get(position); } @Override public int getItemCount() { return fragmentList.size(); } }; vpMain.setAdapter(adapter); // 给ViewPager2设置适配器 new TabLayoutMediator(tlMain, vpMain, false, false, (tab, position) -> { // TabLayout和ViewPager2关联到一起 // tab.setText(menus[position]); // 设置Tab的标题 tab.setCustomView(tabMenu(menuLogos[position], menus[position])); // 设置Tab的图标和标题 }).attach(); // 调用该方法才能真正绑定起来 // for (int i = 0; i < menus.length; i++) { // 设置Tab的图标和标题 // tab = tlMain.getTabAt(i); // tab.setCustomView(tabMenu(menuLogos[i], menus[i])); // } } private void initView() { vpMain = (ViewPager2) findViewById(R.id.vpMain); tlMain = (TabLayout) findViewById(R.id.tlMain); } private View tabMenu(int image, String title) { ImageView ivMenu; TextView tvMenu; View view = LayoutInflater.from(this).inflate(R.layout.tabmenu, null); ivMenu = (ImageView) view.findViewById(R.id.ivMenu); tvMenu = (TextView) view.findViewById(R.id.tvMenu); tvMenu.setText(title); ivMenu.setImageResource(image); return view; } }
其中<ImageView>控件中显示图标,可以使用数组的形式存储图标资源,这里用5个一样的图标表示。
private int[] imageInt = {R.drawable.one, R.drawable.one, R.drawable.one, R.drawable.one, R.drawable.one};
home.png和homes.png
布局文件activity_main.xml
<?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=".MainActivity"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/vpMain" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <com.google.android.material.tabs.TabLayout android:id="@+id/tlMain" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.1" android:background="@color/blue" app:tabIndicatorColor="@color/white" app:tabIndicatorHeight="3dp" /> </LinearLayout>
2、TabLayout的项目布局文件tabmenu.xml
<?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" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/ivMenu" android:layout_width="match_parent" android:layout_height="30dp" /> <TextView android:id="@+id/tvMenu" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="App Title" android:textColor="@color/white" android:textSize="12sp" /> </LinearLayout>
3、每个子项目的图表资源one.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/homes" android:state_enabled="true" android:state_selected="true" /> <item android:drawable="@drawable/home" /> </selector>
4、Android Studio向导创建空白的Fragment
HomeFragment.java
package com.sdbi.smartcityli01.fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sdbi.smartcityli01.R; public class HomeFragment extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; public HomeFragment() { // Required empty public constructor } // TODO: Rename and change types and number of parameters public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_home, container, false); } }
布局文件fragment_home.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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" tools:context=".fragment.HomeFragment"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_blank_fragment" /> </FrameLayout>
运行效果
【注意】
在ViewPager2发布以后,TabLayout加入了一个很是好用的中间类TabLayoutMediator来实现TabLayout与ViewPager2的绑定与滑动联动效果。TabLayoutMediator的构造方法有3种重载形式:
public TabLayoutMediator( @NonNull TabLayout tabLayout, @NonNull ViewPager2 viewPager, @NonNull TabConfigurationStrategy tabConfigurationStrategy) { this(tabLayout, viewPager, /* autoRefresh= */ true, tabConfigurationStrategy); } public TabLayoutMediator( @NonNull TabLayout tabLayout, @NonNull ViewPager2 viewPager, boolean autoRefresh, @NonNull TabConfigurationStrategy tabConfigurationStrategy) { this(tabLayout, viewPager, autoRefresh, /* smoothScroll= */ true, tabConfigurationStrategy); } public TabLayoutMediator( @NonNull TabLayout tabLayout, @NonNull ViewPager2 viewPager, boolean autoRefresh, boolean smoothScroll, @NonNull TabConfigurationStrategy tabConfigurationStrategy) { this.tabLayout = tabLayout; this.viewPager = viewPager; this.autoRefresh = autoRefresh; this.smoothScroll = smoothScroll; this.tabConfigurationStrategy = tabConfigurationStrategy; }
其中第一种需要三个参数:
第一个参数为 TabLayout;
第二个参数为 ViewPager2;
第三个参数是 TabConfigurationStrategy,这是一个接口,里面需要实现一个方法,onConfigureTab(@NonNull TabLayout.Tab tab, int position),这个方法第一个参数是当前的tablayout,第二个是当前的位置。
// 这两种写法等效 new TabLayoutMediator(tlMain, vpMain, false, false, new TabLayoutMediator.TabConfigurationStrategy() { @Override public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) { tab.setCustomView(tabMenu(menuLogos[position], menus[position])); } }).attach(); // 调用该方法才能真正绑定起来 new TabLayoutMediator(tlMain, vpMain, false, false, (tab, position) -> { // TabLayout和ViewPager2关联到一起 tab.setCustomView(tabMenu(menuLogos[position], menus[position])); // 设置Tab的图标和标题 }).attach(); // 调用该方法才能真正绑定起来
TabLayoutMediator还有另外两个构造方法,分别多了两个boolean类型的参数:
boolean autoRefresh:自动刷新
boolean smoothScroll:平滑滚动