TabLayout属性:
app:tabIndicatorColor="#fff" //下方滚动的下划线颜色
app:tabIndicatorHeight="10dp" //滚动的下划线的宽度
app:tabSelectedTextColor="#00f" // tab被选中后,文字的颜色
app:tabTextColor="#fff" // tab默认的文字颜色
app:tabMode="scrollable" // Tab可滚动 默认不可以滚动
app:tabMaxWidth="0dp" //Tab填充
TabLayout依赖:implementation 'com.android.support:design:26.1.0'
选项卡布局:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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="com.lantianbaiyunyk.asus.tablayout.MainActivity">
<android.support.design.widget.TabLayout
android:layout_height="50dp"
android:layout_width="match_parent"
android:id="@+id/course_search_tablayout"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabTextColor="#666666"
app:tabSelectedTextColor="#0414f6"
app:tabIndicatorColor="#0414f6"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:background="#ddd"
>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/search_pager"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
</TableLayout>
MyActivity:
public class MainActivity extends AppCompatActivity {
private TabLayout course_search_tablayout;
private ViewPager search_pager;
private ArrayList<android.support.v4.app.Fragment> mFragments = new ArrayList<>();
private ArrayList<String> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
Fragment1 fragment1 = new Fragment1();
Fragment2 fragment2 = new Fragment2();
Fragment3 fragment3 = new Fragment3();
mFragments.add(fragment1);
mFragments.add(fragment2);
mFragments.add(fragment3);
list.add("页面一");
list.add("页面二");
list.add("页面三");
course_search_tablayout.setupWithViewPager(search_pager);
search_pager.setAdapter(new Adapter(getSupportFragmentManager(),mFragments,list));
}
private void initView() {
course_search_tablayout = (TabLayout) findViewById(R.id.course_search_tablayout);
search_pager = (ViewPager) findViewById(R.id.search_pager);
}
}
Adapter:
public class Adapter extends FragmentPagerAdapter{
private ArrayList<Fragment> fragments;
private ArrayList<String> list;
public Adapter(FragmentManager fm, ArrayList<Fragment> fragments, ArrayList<String> list) {
super(fm);
this.fragments = fragments;
this.list = list;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return list.get(position);
}
}