Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

TabLayout 用法詳解與自訂樣式全攻略

編輯:關於 Android 程式設計

TabLayout 的預設樣式如下:

 app:theme="@style/Widget.Design.TabLayout"

沿著系統定義的這個樣式繼續往下看:

 <style name="Widget.Design.TabLayout" parent="Base.Widget.Design.TabLayout"> <item name="tabGravity">fill</item> <item name="tabMode">fixed</item> </style> <style name="Base.Widget.Design.TabLayout" parent="android:Widget"> <item name="tabMaxWidth">264dp</item> <item name="tabIndicatorColor">?attr/colorAccent</item> <item name="tabIndicatorHeight">2dp</item> <item name="tabPaddingStart">12dp</item> <item name="tabPaddingEnd">12dp</item> <item name="tabBackground">?attr/selectableItemBackground</item> <item name="tabTextAppearance">@style/TextAppearance.Design.Tab</item> <item name="tabSelectedTextColor">?android:textColorPrimary</item> </style>

接著看看系統定義的 Tab 文字樣式(請特別注意 textAllCaps 這個屬性):

 <style name="TextAppearance.Design.Tab" parent="TextAppearance.AppCompat.Button"> <item name="android:textSize">14dp</item> <item name="android:textColor">?android:textColorSecondary</item> <item name="textAllCaps">true</item> </style>

從系統預設樣式可以看出,只要覆寫對應的屬性值,就能讓 TabLayout 貼合我們自己的設計需求。

TabLayout 的基本用法

TabLayout 單獨使用時,既可以在 XML 中靜態宣告 Tab 的數量與樣式,也可以在程式碼中動態添加,例如:

 <android.support.design.widget.TabLayout android:id="@+id/tablayout" android:background="@color/colorPrimary" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Android"/> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="wrap_content" android:icon="@mipmap/ic_launcher"/> </android.support.design.widget.TabLayout>

或者:

 <android.support.design.widget.TabLayout android:id="@+id/tablayout" android:background="@color/colorPrimary" android:layout_width="match_parent" android:layout_height="wrap_content"/>
 private int[] images = new int[]{ R.drawable.ic_account_balance_wallet_black, R.drawable.ic_android_black, R.drawable.ic_account_box_black}; private String[] tabs = new String[]{"小說", "電影", "相聲"}; TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); tabLayout.addTab(tabLayout.newTab().setIcon(images[0]).setText(tabs[0]),true); tabLayout.addTab(tabLayout.newTab().setIcon(images[1]).setText(tabs[1]),false); tabLayout.addTab(tabLayout.newTab().setIcon(images[2]).setText(tabs[2]),false);

實際開發中,TabLayout 最常與 ViewPager 搭配,實現兩者的聯動:

 <android.support.design.widget.TabLayout android:id="@+id/tablayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimary" app:tabGravity="fill" app:tabIndicatorColor="@android:color/holo_orange_dark" app:tabIndicatorHeight="2dp" app:tabMode="fixed" app:tabSelectedTextColor="@android:color/holo_orange_dark" app:tabTextAppearance="@style/CustomTabTextAppearanceStyle" app:tabTextColor="@android:color/white" app:theme="@style/Widget.Design.TabLayout"/> <android.support.v4.view.ViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="match_parent"/>
 TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout); ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager())); tabLayout.setupWithViewPager(viewPager);

值得注意的是:

在 TabPagerAdapter 中必須實作 getPagerTitle(),否則 TabLayout 的 Tab 將不顯示文字。先來看 TabLayout#setupWithPager() 的源碼,可以發現 Tab 的添加是在 populateFromPagerAdapter() 中完成的,該方法會呼叫 PagerAdapter#getPageTitle() 為 Tab 設定文字,若自訂的 Adapter 沒有實作 getPagerTitle(),Tab 就不會顯示文字。源碼如下:

 void populateFromPagerAdapter() { removeAllTabs(); if (mPagerAdapter != null) { final int adapterCount = mPagerAdapter.getCount(); for (int i = 0; i < adapterCount; i++) { addTab(newTab().setText(mPagerAdapter.getPageTitle(i)), false); } // Make sure we reflect the currently set ViewPager item if (mViewPager != null && adapterCount > 0) { final int curItem = mViewPager.getCurrentItem(); if (curItem != getSelectedTabPosition() && curItem < getTabCount()) { selectTab(getTabAt(curItem)); } } } }

另外我們發現,getPagerTitle() 的回傳型別是 CharSequence 而非 String,這代表 Tab 的文字設定可以更靈活——比如塞進一個 SpannableString,把圖片和文字一起放進 Tab。

 @Override public CharSequence getPageTitle(int position) { Drawable image = TablayoutActivity.this.getResources().getDrawable(images[position]); image.setBounds(0, 0, image.getIntrinsicWidth()/2, image.getIntrinsicHeight()/2); ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM); SpannableString ss = new SpannableString(" "+tabs[position]); ss.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return ss; } 

但這時 Tab 卻什麼都沒顯示,一片空白。回頭看前面提到的系統預設樣式:<item name="textAllCaps">true</item>,正是它阻止了 ImageSpan 的渲染。我們只要把 textAllCaps 改為 false 即可:

 <style name="CustomTabTextAppearanceStyle" parent="TextAppearance.Design.Tab"> <item name="textAllCaps">false</item> </style>

  修改 Indicator 的長度:

從 TabLayout 的源碼可以看到,Indicator 是在其內部類 SlidingTabStrip 中繪製的,而 SlidingTabStrip 繼承自 LinearLayout,源碼如下:

 @Override public void draw(Canvas canvas) { super.draw(canvas); // Thick colored underline below the current selection if (mIndicatorLeft >= 0 && mIndicatorRight > mIndicatorLeft) { canvas.drawRect(mIndicatorLeft, getHeight() - mSelectedIndicatorHeight, mIndicatorRight, getHeight(), mSelectedIndicatorPaint); } }

在 onDraw() 中主要就是畫一個矩形,其寬度由 mIndicatorLeft 和 mIndicatorRight 決定,而這兩個值又來自 SlidingTabStrip 的子 View(每個子 View 相當於一個 Tab)。因此,我們可以透過修改子 View 的 margin 來間接調整 mIndicatorLeft 的值。

 public void setIndicator(TabLayout tabs, int leftDip, int rightDip) { Class<?> tabLayout = tabs.getClass(); Field tabStrip = null; try { tabStrip = tabLayout.getDeclaredField("mTabStrip"); } catch (NoSuchFieldException e) { e.printStackTrace(); } tabStrip.setAccessible(true); LinearLayout llTab = null; try { llTab = (LinearLayout) tabStrip.get(tabs); } catch (IllegalAccessException e) { e.printStackTrace(); } int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics()); int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics()); for (int i = 0; i < llTab.getChildCount(); i++) { View child = llTab.getChildAt(i); child.setPadding(0, 0, 0, 0); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1); params.leftMargin = left; params.rightMargin = right; child.setLayoutParams(params); child.invalidate(); } }

接著在程式碼中呼叫即可,但要注意:必須在 TabLayout 渲染完成之後再呼叫,可以借助 view.post() 來實現:

 tabLayout.post(new Runnable() { @Override public void run() { setIndicator(tabLayout, 20, 20); } });

最終效果如下:

自訂 TabLayout 的 TabItem 及點擊事件

TabLayout 的 API 並沒有直接提供 TabItem 的點擊事件,如果想做出下圖的效果,該怎麼辦?

先自訂一個 TabItem:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal"> <TextView android:id="@+id/txt_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:textSize="14sp" /> <ImageView android:id="@+id/img_title" android:src="@drawable/indicator" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" /> </LinearLayout>

在自訂的 Adapter 中定義一個 getTabView 方法:

 public View getTabView(int position){ View view = LayoutInflater.from(context).inflate(R.layout.tab_item, null); TextView tv= (TextView) view.findViewById(R.id.textView); tv.setText(tabTitles[position]); ImageView img = (ImageView) view.findViewById(R.id.imageView); img.setImageResource(imageResId[position]); return view; }

  重新設定點擊事件:

 viewPager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(viewPager); for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); if (tab != null) { tab.setCustomView(pagerAdapter.getTabView(i)); if (tab.getCustomView() != null) { View tabView = (View) tab.getCustomView().getParent(); tabView.setTag(i); tabView.setOnClickListener(mTabOnClickListener); } } } viewPager.setCurrentItem(1);

以上就是本文介紹的 TabLayout 用法與自訂樣式,希望對大家有所幫助。若有疑問歡迎留言,我會及時回覆,也感謝大家對本站的支持!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved