The problem is, sliding layout do not set item's state as selected
. Here is my approach to solve the problem.
1) Create COLOR selector (ColorStateList
) for your view. You can imagine it this way:
/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) Place created selector to your item's view textColor
(or other required) attribute:
<TextView
...
android:textColor="@color/tab_text_color"
... />
3) Do this changes in file 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;
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…