6

我有一個工作TabLayout,並且我試圖在更改選項卡時動態更新選項卡文本顏色。要做到這一點,我呼籲我的TabLayout的setTabTextColors()方法,例如:當試圖更改文本顏色時,TabLayout.setTabTextColors()不工作

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
    @Override 
    public void onTabSelected(TabLayout.Tab tab) { 
     tabLayout.setTabTextColors(newColorStateList); 
    } 

    (...) 
}); 

出於某種原因,文本顏色不更新。有誰知道如何動態更新標籤文本顏色?

我正在使用設計支持庫v22.2.0。

回答

3

它終於固定設計支持庫22.2.1。

 tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
      @Override 
      public void onTabSelected(TabLayout.Tab tab) { 
      tabLayout.setTabTextColors(getResources().getColor(R.color.normal), getResources().getColor(R.color.selected)); 

      try { 
       // FIXME: 20.7.2015 WORKAROUND: https://code.google.com/p/android/issues/detail?id=175182 change indicator color 
       Field field = TabLayout.class.getDeclaredField("mTabStrip"); 
       field.setAccessible(true); 
       Object value = field.get(tabLayout); 

       Method method = value.getClass().getDeclaredMethod("setSelectedIndicatorColor", Integer.TYPE); 
       method.setAccessible(true); 
       method.invoke(value, getResources().getColor(R.color.selected)); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      } 

     ... 
     } 
4

經過一番調查,似乎TabLayout內的文本瀏覽器在創建後並沒有更新它們的顏色。

我想出的解決方案是通過TabLayout的子視圖並直接更新顏色。

public static void setChildTextViewsColor(ViewGroup viewGroup, ColorStateList colorStateList) { 
    for (int i = 0; i < viewGroup.getChildCount(); i++) { 
     View child = viewGroup.getChildAt(i); 

     if (child instanceof ViewGroup) { 
      setChildTextViewsColor((ViewGroup) child, colorStateList); 
     } else if (child instanceof TextView) { 
      TextView textView = (TextView) child; 
      textView.setTextColor(colorStateList); 
     } 
    } 
} 

然後,在OnTabSelectedListener:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { 
     @Override 
     public void onTabSelected(TabLayout.Tab tab) { 
      setChildTextViewsColor(tabLayout, newColorStateList); 
     } 

     (...) 
    }); 
0

此外,請確保您不要使用單獨的xml文件來設置選項卡樣式。像這樣的東西,就像我有(custom_tab.xml):

TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null); 
    tabOne.setText(R.string.tab_response); 
    tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.tab_bar_icon_response, 0, 0); 
    tabLayout.getTabAt(0).setCustomView(tabOne); 
相關問題