2011-06-24 47 views
2

這是我第一篇文章。 我必須在運行時更改TextView's文字顏色。有一種方法TextView.setTextColor(int),但它不適用於不在資源中的int值。

例如,在運行時計算出的顏色(如0xFF0000 (RGB),不存在於R.color中)不起作用。 TextView未呈現。
我已經採取了看看這個Android源代碼,並有兩種方法,他們沒有接受rgb int values作爲參數:TextView:無法在運行時更改文字顏色

/** 
* Sets the text color for all the states (normal, selected, 
* focused) to be this color. 
* 
* @attr ref android.R.styleable#TextView_textColor 
*/ 
@android.view.RemotableViewMethod 
public void setTextColor(int color) { 
    mTextColor = ColorStateList.valueOf(color); 
    updateTextColors(); 
} 

/** 
* Sets the text color. 
* 
* @attr ref android.R.styleable#TextView_textColor 
*/ 
public void setTextColor(ColorStateList colors) { 
    if (colors == null) { 
     throw new NullPointerException(); 
    } 

    mTextColor = colors; 
    updateTextColors(); 
} 

所以沒有這樣做的呢?也許延伸TextView

在此先感謝。

+0

問題是什麼?通過使用android.graphics.Color類中的常量和方法,可以在UI線程中的任何位置設置文本顏色。 –

回答

6

我認爲這個問題可能是你沒有設置顏色的alpha值。

TextView.setTextColor()不接受0xRRGGBB值。相反,它接受0xAARRGGBB。無論何時你把"0xFF0000",你實際上給的價值"0x00FF0000",它給了它一個「0」的alpha值,這就是爲什麼TextView沒有呈現。因此,而不是0xFF0000,嘗試將其設置爲0xFFFF0000。

或者,您可以使用Android的Color類。方法「Color.rgb(int,int,int)」隱式指定255的alpha值,因此調用"Color.rgb(255, 0, 0)"應爲文本生成紅色值。

+0

但[sdk文檔](http://developer.android.com/reference/android/widget/TextView.html#attr_android:textColor)表示它也接受RGB。 – bluefalcon

+0

這是針對xml屬性的。該方法沒有。只需將值「0xFF0000」傳入setTextView(int)方法將使文本不可見。 – DeeV

+0

呵呵我一直認爲兩者應該是一樣的......但我從來沒有嘗試過。 – bluefalcon

1

請嘗試以下

textView.setTextColor(Color.rgb(0,0,0)); 
3

試試這個

採取TextView實例,並調用setTextColor方法

假設你有TextView的id爲myTextView,那麼首先獲得它的實例

TextView myText = (TextView) findViewById(R.id.myTextView); 

然後調用setTextColor方法

myText .setTextColor(android.graphics.Color.RED); 

myText .setTextColor(android.graphics.Color.rgb(int red,int green,int blue);