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的基本用法
TabLayout独立使用使用时,可以xml布局中静态添加tab个数及其样式,也可以动态添加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联合使用,实现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()中实现,实现源码如下,可以看出该方法调用了PagerAdpater#getPagerTitle()为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的文本信息的设置将变得更加灵活,比如设置一个SpanableString,将图片和文本设置Tab的文本.
@OverrIDe public CharSequence getPageTitle(int position) { Drawable image = TablayoutActivity.this.getResources().getDrawable(images[position]); image.setBounds(0,image.getIntrinsicWIDth()/2,image.getIntrinsicHeight()/2); ImageSpan imageSpan = new ImageSpan(image,ImageSpan.AliGN_BottOM); SpannableString ss = new SpannableString(" "+tabs[position]); ss.setSpan(imageSpan,1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return ss; }
但是Tab缺没有显示任何信息,一片空白,从上面提到的TabLayout的系统默认样式中我们发现: <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中绘制,而SlingTabStrip类继承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()中主要是就绘制一个Rect,并且宽度是根据mIndicatorleft和mIndicatorRight设置的,而mIndicatorleft等的宽度来自SlIDingTabStrip的child,而Child就相当于一个Tab,这样我们就通过修改Child的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); 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及TabItem的点击事件
在TabLayout的API是没有提供TabItem点击事件的方法,如果我们想实现如下效果图,怎么办?
先自定义一个TabItem:
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://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用法详解及自定义样式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的TabLayout用法详解及自定义样式全部内容,希望文章能够帮你解决TabLayout用法详解及自定义样式所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)