在 tablayout 中的选项卡上增加宽度自定义视图
Increase width custom view on tab in tablayout
我目前有一个带有自定义标签的标签布局。目前选项卡显示很好,唯一的问题是选项卡似乎仅限于 tablayout 选项卡大小,在下一个选项卡之间留下 space。有没有办法使选项卡上的自定义视图与 tablayouts 选项卡大小相匹配?请告诉我。
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp">
textview element
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
TabLayout tabLayout = findViewById(R.id.tabLayout);
new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setCustomView(R.layout.custom_tab);
//get textview and set custom text
//set background color
}
}).attach();
经过一番挖掘,我找到了答案。问题是在使用自定义视图时,tablayout 会将视图膨胀到最大宽度和高度。添加与完整 tablayout 选项卡宽度和高度完全匹配的背景的最佳方法是使用 tablayout xml tabBackground 并添加一个包含选择器以及 textColor 和 textSelectedColor 的可绘制对象。按照本教程了解更多信息:https://www.thecodecity.com/2016/12/changing-background-color-of-tab.html#:~:text=%20How%20to%20change%20tab%20color%20in%20TabLayout,create%20as%20the%20background%20of%20the...%20More%20
我目前有一个带有自定义标签的标签布局。目前选项卡显示很好,唯一的问题是选项卡似乎仅限于 tablayout 选项卡大小,在下一个选项卡之间留下 space。有没有办法使选项卡上的自定义视图与 tablayouts 选项卡大小相匹配?请告诉我。
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="50dp">
textview element
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
TabLayout tabLayout = findViewById(R.id.tabLayout);
new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setCustomView(R.layout.custom_tab);
//get textview and set custom text
//set background color
}
}).attach();
经过一番挖掘,我找到了答案。问题是在使用自定义视图时,tablayout 会将视图膨胀到最大宽度和高度。添加与完整 tablayout 选项卡宽度和高度完全匹配的背景的最佳方法是使用 tablayout xml tabBackground 并添加一个包含选择器以及 textColor 和 textSelectedColor 的可绘制对象。按照本教程了解更多信息:https://www.thecodecity.com/2016/12/changing-background-color-of-tab.html#:~:text=%20How%20to%20change%20tab%20color%20in%20TabLayout,create%20as%20the%20background%20of%20the...%20More%20