2012-10-03 46 views
15

我正在創建一個使用Android 4.0的應用程序。 我想知道是否可以更改交換機中文本的文本顏色。如何更改Android中開關的textcolor

我試過設置文本顏色,但它不起作用。

任何想法?

在此先感謝!

+1

發佈您的代碼.. –

+0

有沒有具體的代碼,它只是在佈局中的一個開關,通過ID找到。而在代碼中,我設置了switch.setTextColor(Color.WHITE); –

回答

57

必須使用android:switchTextAppearance屬性,如:

android:switchTextAppearance="@style/SwitchTextAppearance" 

和風格:

<style name="SwitchTextAppearance" parent="@android:style/TextAppearance.Holo.Small"> 
    <item name="android:textColor">@color/my_switch_color</item> 
</style> 

你也可以做到這一點的代碼,也使用上述樣式:

mySwitch.setSwitchTextAppearance(getActivity(), R.style.SwitchTextAppearance); 

...至於setTextColorSwitch - 這個顏色將用於如果你的SwitchTextAppearance風格不提供textColor

您可以檢查它在Switch源代碼setSwitchTextAppearance

ColorStateList colors; 
    int ts; 

    colors = appearance.getColorStateList(com.android.internal.R.styleable. 
      TextAppearance_textColor); 
    if (colors != null) { 
     mTextColors = colors; 
    } else { 
     // If no color set in TextAppearance, default to the view's textColor 
     mTextColors = getTextColors(); 
    } 

    ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable. 
      TextAppearance_textSize, 0); 
    if (ts != 0) { 
     if (ts != mTextPaint.getTextSize()) { 
      mTextPaint.setTextSize(ts); 
      requestLayout(); 
     } 
    } 
+1

我想知道爲什麼couldn他們只是讓'setTextColor'正常工作,而不是所有這些膨脹。 –

0

TextView.setTextColor()從xml文件中獲取表示顏色(例如0xFFF5DC49)而不是資源ID的int。在活動中,你可以這樣做:

textView1.setTextColor(getResources().getColor(R.color.mycolor))

之外,你還需要一個Context例如活動的。

textView1.setTextColor(context.getResources().getColor(R.color.mycolor))

欲瞭解更多請參考this

+1

您好,首先感謝您的回覆!這不是我正在尋找的答案,我爲它的textviews和editTexts工作。但我需要它的開關,我不知道如何.. –

+1

實際上'setTextColor'不用於'開關',除非'android:switchTextAppearance'提供的樣式沒有定義textColor – imbryk

0

我覺得你要看看你正在使用你的應用程序的主題。因爲開關的顏色是主題afaik的責任。所以我建議你看看你如何改變一個主題的設置。或者您可以使用新顏色創建自定義主題。

相關問題