安卓 专高 day07 TabLayout
作者:互联网
安卓 专高 day07 TabLayout
TabLayout简介
Tablayout继承自HorizontalScrollView用于页面切换指示器
TabLayout 是属于 com.android.support:design 包的控件,所以需要依赖该包
implementation 'com.android.support:design:28.0.0'
Fragment+ViewPager+TabLayout组合使用
activity的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"
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>
TabLayout 的几个常用属性值
// 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");
//适配器
Myfragmentadapter myfragmentadapter = new Myfragmentadapter(getSupportFragmentManager(), list, list2);
vp.setAdapter(myfragmentadapter);
//绑定
tab.setupWithViewPager(vp);
}
}
适配器Myfragmentadapter
public class Myfragmentadapter extends FragmentStatePagerAdapter {
private List<Fragment> list;
private List<String> list2;
public Myfragmentadapter(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);
}
}
内容fragment创建出来就行内容不需要改动
标签:专高,day07,安卓,list,private,list2,public,app,TabLayout 来源: https://blog.csdn.net/zxsenqiu/article/details/104533738