我正在使用Google的SlidingTabLayout(https://developer.android.com/samples/SlidingTabsBasic/src/com.example.android.common/view/SlidingTabLayout.html)。
它工作正常,但是我想要的是将所选标题以粗体显示并使用不同的颜色...
关于此帖子:SlidingTabLayout中的自定义未选择的选项卡文本颜色
我使用选择器在drawable中创建了一个text_tab.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/selected" android:state_selected="true" />
<item android:color="@android:color/unselected" />
</selector>
当我在populateTabStrip()方法中时
tabTitleView.setTextColor(getResources().getColorStateList(R.drawable.text_tab));
颜色始终是未选中的颜色之一。
我可能做错了什么,或者还有另一种方式来自定义所选标签标题。
有人有主意吗?
谢谢
问题是,滑动布局不会将项目的状态设置为selected
。这是我解决问题的方法。
1)为您的视图创建COLOR选择器(ColorStateList
)。您可以这样想象:
/res/color/tab_text_color.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white" android:state_selected="true"/>
<item android:color="@color/black"/>
</selector>
2)将创建的选择器放置到项目的视图textColor
(或其他必需的)属性中:
<TextView
...
android:textColor="@color/tab_text_color"
... />
3)在文件SlidingTabLayout.java中进行以下更改:
View oldSelection = null; // new field indicating old selected item
// method to remove `selected` state from old one
private void removeOldSelection() {
if(oldSelection != null) {
oldSelection.setSelected(false);
}
}
// improve method scrollToTab() as follows
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
if(positionOffset == 0 && selectedChild != oldSelection) { // added part
selectedChild.setSelected(true);
removeOldSelection();
oldSelection = selectedChild;
}
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private void populateTabStrip() {
removeOldSelection(); // add those two lines
oldSelection = null;
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句