文章目录
ViewPager2 + TabLayout + TabItem
在写Android项目的时候通常会有编写底部导航栏,然后在利用碎片来到指定的部分 以前经常使用的是ViewPager 而现在有了ViewPager2,在写项目的时候觉得也需要提升一下自己的新技术,就开始把ViewPager开始着手换成ViewPager2
Viewpager + TabLayout + TabItem
首先我们先来看代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FFF"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#00000000"
app:tabRippleColor="#00000000"
app:tabSelectedTextColor="#FFCCCC"
app:tabTextColor="#929299">
<com.google.android.material.tabs.TabItem
android:id="@+id/item_chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="@drawable/fragment_home"
android:text="首页" />
<com.google.android.material.tabs.TabItem
android:id="@+id/item_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="@drawable/fragment_shopping"
android:text="购物车" />
<com.google.android.material.tabs.TabItem
android:id="@+id/item_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:icon="@drawable/fragment_person"
android:text="我的" />
</com.google.android.material.tabs.TabLayout>
</RelativeLayout>
可以看到上面代码,我们使用TabLayout然后里面的TabItem直接设置了一个背景图和文字,外面和ViewPager并列
private TabLayout tabLayout;
private ViewPager viewPager;
final String[] titleArray = new String[]{
"首页", "购物车", "我的"};
public List<Fragment> fragmentList;
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//添加碎片,具体碎片自行创建
fragment.add(new FragmentOne());
fragment.add(new FragmentTwo());
//然后是一个适配器 然后是viewpager绑定这个碎片的适配器
FragmentAdapter adapter = new
FragmentAdapter(getSupportFragmen