简体   繁体   English

如何在TabLayout中自定义选定的选项卡指示器?

[英]How can I customize the selected tab indicator in a TabLayout?

I would like to change the selected tab indicator of a TabLayout, with a custom icon, that should follow the same behavior (as the user slides towards the next tab, the icon moves accordingly). 我想更改带有自定义图标的TabLayout的选定选项卡指示器,该指示器应该遵循相同的行为(当用户向下一个选项卡滑动时,图标会相应移动)。

There's no default method in the class since you can only reach a tab's layout customization. 该类中没有默认方法,因为您只能实现选项卡的布局自定义。 I decided to take a look to the TabLayout's source code , but 1) I can't find in the class the point in which there's the definition of the shape that the tab indicator will assume when drawn, and 2) I can't even fully import the class. 我决定看一下TabLayout的源代码 ,但是1)我无法在类中找到定义制表符指示符将在绘制时采用的形状定义的要点,以及2)我什至无法完全导入该类。 I also would like – if possible – to avoid any third-party library, since the project is already very heavy. 我还希望-如果可能的话-避免使用任何第三方库,因为该项目已经非常繁重。

Do you have any suggestions? 你有什么建议吗? I can see two possible approaches: 我可以看到两种可能的方法:

  1. finding a way to customize the TabLayout class in order to replace the "squarish shape" with a custom icon. 寻找一种自定义TabLayout类的方法,以用自定义图标替换“方形”。
  2. finding a way to coordinate the user's touch gestures on the ViewPager with the movements of a custom View (ie. my icon). 寻找一种方法来协调用户在ViewPager上的触摸手势与自定义View(即我的图标)的移动。

One solution I can think of at the moment is you'll have to create a custom view layout file that represents your desired "selected tab" and annotate android:tabStripEnabled="false" to your TabLayout in the XML file. 我目前可以想到的一种解决方案是,您必须创建一个自定义视图布局文件来表示所需的“选定的选项卡”,然后将android:tabStripEnabled="false"注释到XML文件中的TabLayout中。

After that, you'll have to register a listener on the tablayout instance, and check which index is being selected, and with the given index, call TabLayout.getTabAt(i).setCustomView(yourSelectedCustomView) . 之后,您必须在tablayout实例上注册一个侦听器,并检查选择了哪个索引,并使用给定索引调用TabLayout.getTabAt(i).setCustomView(yourSelectedCustomView)

Take a look here on how to create a custom view for TabLayout : https://stackoverflow.com/a/48258731/4974461 在这里看看如何为TabLayout创建自定义视图: https : TabLayout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM