如何在 TabLayout 中的选项卡之间添加边距? [英] How to add margin between tabs in TabLayout?

查看:34
本文介绍了如何在 TabLayout 中的选项卡之间添加边距?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 TabLayout 中的选项卡之间添加边距?我曾尝试为 Widget.Design.TabLayout 使用自定义样式,但有一些属性仅与填充相关,但没有边距.

Is there a way to add margin between the tabs in a TabLayout? I've tried with using a custom style for Widget.Design.TabLayout, but there are properties only related to padding, but no margins.

推荐答案

好的伙计们,在花了 2-3 个小时之后,我终于找到了解决方案.

Ok mates, after spending 2-3 hours on that I finally found a solution.

如果您使用的是 TabLayout,则无法通过使用样式等方式为选项卡添加边距.(早前@Connecting life with Android)

If you are using TabLayout there is no way to add margins to the tabs by using styles and so on. (as @Connecting life with Android earlier)

但是,您可以通过编写一些 Java 代码来做到这一点.总而言之,您的代码应该与该代码类似:

But, you can do that by writing some Java code. All in all your code should look similar to that one:

            for(int i=0; i < mTabLayout.getTabCount(); i++) {
                View tab = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i);
                ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
                p.setMargins(0, 0, 50, 0);
                tab.requestLayout();
            }

为了将每个选项卡作为视图,我们必须首先获取包含它们的容器.在这种情况下,TabLayout 使用 SlidingTabStrip 作为标签的容器.SlidingTabStrip 是 TabLayout 的第一个孩子:

In order to get each and every tab as a View we have to first get the container which contains them. In this case the TabLayout is using a SlidingTabStrip as a container for the tabs. The SlidingTabStrip is the first child of the TabLayout:

View tab = ((ViewGroup) mTabLayout.getChildAt(0))

在这个小细节之后,一切都很简单.

And after this small detail, everything is pretty straight forward.

这篇关于如何在 TabLayout 中的选项卡之间添加边距?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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