Android-快速实现ViewPager+Tablayout的联动效果android
在项目开发中不少场景都会碰到tab栏切换的效果,实现的思路也有不少种,tabhost+fragment,radionbtton+viewpager等方式均可以实现,这里就说下tablayout+viewpager的实现方式;tablayout是android5.0推出来的一个MaterialDesign风格的控件,是专门用来实现tab栏效果的;功能强大,使用方便灵活;app
引入依赖库:ide
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:design:26.1.0'布局
布局文件:字体
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutcode
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bg" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/tablayout" android:layout_width="match_parent" android:layout_height="50dp" android:layout_gravity="top|center" app:tabMode="fixed" app:tabGravity="fill" app:tabTextColor="@color/black999" app:tabSelectedTextColor="@color/orange" app:tabIndicatorColor="@color/orange" app:tabIndicatorHeight="4dp"/> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white"> </android.support.v4.view.ViewPager>
</LinearLayout>xml
tablayout提供了不少的属性能够设置:utf-8
app:tabIndicatorColor 指示器颜色
app:tabTextColor tab栏字体颜色
app:tabSelectedTextColor tab栏字体被选颜色
app:tabIndicatorHeight 指示器高度
app:tabBackground tab背景颜色
app:tabMaxWidth tab栏最大宽度
app:tabTextAppearance tab栏字体样式
app:tabMinWidth tab栏最小宽度开发
这些属性能够下xml中设置,也能够使用代码进行设置;须要注意这两个属性:get
app:tabMode="";有scrollable和fixed两个属性值
scrollable:可滑动;
fixed:不能滑动,平分tabLayout宽度;
app:tabGravity="";有center和fill两个属性值
fill:tabs平均填充整个宽度;
center:tab居中显示;
页面实现方式:
public static final String[] tabTitles = new String[]{"所有", "代付款", "代发货", "配送中"};
private TabLayout mTabLayout; private ViewPager mViewPager; private List<MyOrderFragment> mFragments = new ArrayList<MyOrderFragment>();
mTabLayout = (TabLayout) findViewById(R.id.tablayout);
mViewPager = (ViewPager) findViewById(R.id.viewpager); tv_title.setText("全部订单"); for (int i = 0; i < tabTitles.length; i++) { mFragments.add(MyOrderFragment.createFragment(tabTitles[i],activity)); } //为ViewPager设置FragmentPagerAdapter mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) { @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } /** * 为TabLayout中每个tab设置标题 */ @Override public CharSequence getPageTitle(int position) { return tabTitles[position]; } }); //TabLaout和ViewPager进行关联 mTabLayout.setupWithViewPager(mViewPager);
其中MyOrderFragment就是咱们装载的页面 ,这样就能够快速的实现tablayout和viewpager相互关联。
作个简单的记录~