SlidingTabLayout で選択されたタブのテキストの色をカスタマイズする 質問する

SlidingTabLayout で選択されたタブのテキストの色をカスタマイズする 質問する

私は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));

色は常に選択されていない色になります...

おそらく何か間違っているか、選択したタブのタイトルをカスタマイズする別の方法があるのか​​もしれません。

誰かアイデアを持っていますか?

ありがとう

ベストアンサー1

問題は、スライディング レイアウトがアイテムの状態を設定しないことですselected。この問題を解決するための私のアプローチは次のとおりです。

1) 作成するビューのセレクター ( ColorStateList) です。次のように考えることができます。

/res/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;
    ...
}

おすすめ記事