TabLayout提供按钮来切换不同的页面,比如以下页面:
image
TabLayout的一些属性的使用:
app:tabIndicatorFullWidth="false"
app:tabIndicatorHeight="4dp"
app:tabIndicatorColor="#915222"
app:tabTextColor="#915222"
app:tabTextAppearance="@style/maintabtextstyle"
app:tabIndicator="@drawable/tabindicator"
app:tabIndicatorFullWidth:设置指针长度,当为false时自适应宽度,也就是会跟文字的长度相匹配,为true的时候,长度为每个tab的长度
app:tabTextAppearance:设置tab中文字的样式,比如:
<style name="maintabtextstyle">
<item name="android:textSize">19sp</item>
<item name="android:fontFamily">@font/sourcehanserifcnmedium</item>
</style>
app:tabIndicator:设置指针样式,比如可以定义一个select来设置指针圆角
TabLayout和ViewPager联动
ViewPager的Adapter除了正常的方法外,再重写一个getPageTitle方法作为TabLayout的标题
public class FragmentFuncAdapter extends FragmentStatePagerAdapter {
private List<Fragment> arrfragment;
private List<String> arrtitles;
public FragmentFuncAdapter(FragmentManager fm, List<Fragment> arrfragment, List<String> arrtitle) {
super(fm);
this.arrfragment = arrfragment;
this.arrtitles = arrtitle;
}
@Override
public Fragment getItem(int i) {
return arrfragment.get(i);
}
@Override
public int getCount() {
return arrfragment.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return arrtitles.get(position);
}
}
最后调用setupWithViewPager方法把两者关联
tblbottom.setupWithViewPager(vpcontent);
手动定义TabLayout的点击方法
tbqm.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int pos = tab.getPosition();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content, arrqmfragment.get(pos));
transaction.commit();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
<?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:id="@+id/contenttitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="17dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:fitsSystemWindows="true"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tbtest"/>
</LinearLayout>
TabLayout tbtest = findViewById(R.id.tbtest);
tbtest.addTab(tbtest.newTab().setText("Tab1"));
tbtest.addTab(tbtest.newTab().setText("Tab2"));
手机赚钱怎么赚,给大家推荐一个手机赚钱APP汇总平台:手指乐(http://www.szhile.com?from=js),辛苦搬砖之余用闲余时间动动手指,就可以日赚数百元