安卓TabLayout
TabLayout的简介
Fragment+ViewPager+TabLayout组合使用
简介
Tablayout继承自HorizontalScrollView用于页面切换指示器
TabLayout 是属于 com.android.support:design 包的控件,所以需要依赖该包
implementation 'com.android.support:design:28.0.0'
Fragment+ViewPager+TabLayout组合使用
<?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"
tools:context=".MainActivity"
android:orientation="vertical"
>
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:tabSelectedTextColor="@color/colorAccent"
>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
常用属性值
// app:tabBackground 标签布局的背景色
// app:tabIndicatorColor 指示器的颜色
// app:tabIndicatorHeight 指示器的高度(如果不需要指示器可以设置为0dp)
// app:tabMode 显示模式:默认 fixed(固定),scrollable(可横向滚动)
// app:tabPadding 标签内边距
// app:tabSelectedTextColor 标签选中的文本颜色
// app:tabTextAppearance 标签文本样式
// app:tabTextColor 标签未选中的文本颜色
Activity的Java文件
public class MainActivity extends AppCompatActivity {
private TabLayout tab;
private ViewPager vp;
private List<Fragment> list = new ArrayList<>();
private List<String> list2 = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab = (TabLayout) findViewById(R.id.tab);
vp = (ViewPager) findViewById(R.id.vp);
list.add(new Fragment1());
list.add(new Fragment2());
list2.add("标题1");
list2.add("标题2");
//适配器
Myadapter myadapter = new Myadapter(getSupportFragmentManager(), list, list2);
vp.setAdapter(myfragmentadapter);
tab.setupWithViewPager(vp);
}
适配器
public class Myadapter extends FragmentStatePagerAdapter {
private List<Fragment> list;
private List<String> list2;
public Myadapter (FragmentManager fm, List<Fragment> list, List<String> list2) {
super(fm);
this.list = list;
this.list2 = list2;
}
@Override
public Fragment getItem(int i) {
return list.get(i);
}
@Override
public int getCount() {
return list.size();
}
//关联
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return list2.get(position);
}
}