软件编程
位置:首页>> 软件编程>> Android编程>> 基于TabLayout中的Tab间隔设置方法(实例讲解)

基于TabLayout中的Tab间隔设置方法(实例讲解)

作者:Dway  发布时间:2023-12-05 06:56:10 

标签:TabLayout,Tab,间隔,设置

TabLayout和ViewPager搭配使用,是有很多方便性,但是TabLayout这东西还是有很多被人吐槽的地方。

这里只讲怎么设置tab之间的间隔,网上找了一堆方法,什么padding和margin的啥都没用,没办法,想用TabLayout只能自己想办法了。效果如下:

基于TabLayout中的Tab间隔设置方法(实例讲解)

一、实现方法,既然这东西不好设置,那就直接在背景上做点事情,布局代码如下:


<android.support.design.widget.TabLayout
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:id="@+id/tl_download_tabs"
 android:layout_width="wrap_content"
 android:layout_height="30dp"
 android:layout_marginTop="10dp"
 android:layout_gravity="center_horizontal"
 android:overScrollMode="never"
 app:tabMode="fixed"
 app:tabPaddingStart="30dp"
 app:tabPaddingEnd="30dp"
 app:tabIndicatorHeight="0dp"
 app:tabBackground="@drawable/download_tab_bg_selector"
 app:tabSelectedTextColor="#000000"
 app:tabTextColor="#ffffff"/>

二、其中关键的地方就在背景的selector上,代码如下:


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true">
 <!--<shape>
  <solid android:color="#ffffff"/>
  <corners android:topLeftRadius="10dp" android:topRightRadius="10dp" />
 </shape>-->
 <!--为了让TabLayout内部的Tab有间隔,暂时找不到其他设置方法,只能在背景图形里面设置间隔-->
 <layer-list>
  <item>
   <shape>
    <solid android:color="@android:color/transparent"/>
   </shape>
  </item>
  <item android:left="5dp" android:right="5dp">
   <shape>
    <corners android:topLeftRadius="10dp" android:topRightRadius="10dp" />
    <solid android:color="#ffffff"/>
   </shape>
  </item>
 </layer-list>
</item>
<item android:state_selected="false">
 <!--<shape>
  <solid android:color="#bcbcbc"/>
  <corners android:topLeftRadius="10dp" android:topRightRadius="10dp" />
 </shape>-->
 <layer-list>
  <item>
   <shape>
    <solid android:color="@android:color/transparent"/>
   </shape>
  </item>
  <item android:left="5dp" android:right="5dp">
   <shape>
    <corners android:topLeftRadius="10dp" android:topRightRadius="10dp" />
    <solid android:color="#bcbcbc"/>
   </shape>
  </item>
 </layer-list>
</item>
</selector>

注释掉的地方是原来没间隔的selector,这里直接给背景设置了个左右的padding,效果杠杠的。

缺点:如果间隔过大的话,那这种方式就有一点的缺陷了,就是点击到空白处,也能选中tab。

不过对于间隔不是很大的,基本是感觉不出来的。

三、Activity的使用就很简单了:


TabLayout mTabLayout = (TabLayout) findViewById(R.id.tl_download_tabs);
 mTabLayout.addTab(mTabLayout.newTab().setText("已下载"));
 mTabLayout.addTab(mTabLayout.newTab().setText("下载中"));
 mTabLayout.setupWithViewPager(mViewPager);

四、原来是线性布局下,放着TabLayout和ViewPager,试着在TabLayout外嵌套多一个RelativeLayout,发现出来的效果Tab的文字不显示了,至于网上说的调换addTab和setupWithViewPager的顺序也是坑,可以看到显示,但是出现了更离谱的情况,前面两个空白,后面还多了两个正常的,反正是很奇葩。

最后还是得在Adapter中去处理,把以下方法重写下就可以了,其实这样可能更合理些,至少能保证Tab的数量和ViewPager的页数是一致的。


@Override
 public CharSequence getPageTitle(int position) {
  if(position == 0){
   return "已下载";
  }else if(position == 1){
   return "下载中";
  }
  return "";
 }

来源:http://blog.csdn.net/lin_dianwei/article/details/78806816

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com