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相互關聯。
作個簡單的記錄~