Android TabLayout自定义指标宽度 [英] Android TabLayout custom indicator width

查看:798
本文介绍了Android TabLayout自定义指标宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想减小指示器的宽度-例如,使其宽度不是整个标签宽度,而是标签宽度的1/2.
这就是我要做的,所以我不想下载一些自定义库并在可以执行此操作的地方搜索.

I want to reduce width of indicator - for example, make it's width not whole tab width, but 1/2 of tab width.
That's all I need to do, so I don't want to download some custom library and search where I can do this.

这是做到这一点的一种方法,还是我自己写一个这样的观点?

Is it a way to do this or I should write such view by myself?

推荐答案

尝试一下.

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();  
   }  
}

然后

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


我的修改不包含反射(应设置自定义视图!).

for (int i = 0; i < tabs.getTabCount(); i++) {
    TabLayout.Tab tab = tabs.getTabAt(i);
    if (tab != null) {
        View customView = tab.getCustomView();
        if (customView != null) {
            View targetViewToApplyMargin = (View) customView.getParent();
            ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) targetViewToApplyMargin.getLayoutParams();

            layoutParams.rightMargin = totalTabMargin;
                    targetViewToApplyMargin.setLayoutParams(layoutParams);
        }
    }
}

这篇关于Android TabLayout自定义指标宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆