2016-09-27 92 views
2

最近我改變了一點我的應用程序,並且出於某種原因,我不明白「setTextColor」方法似乎不再適用。以編程方式在Android庫中的TextView中設置setTextColor

在我的XML中,我有一個列表視圖,我以編程方式在此列表視圖中添加TextViews。

XML:

<LinearLayout 
     android:id="@+id/activity_game_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="left|top" 
     android:orientation="vertical" 
     android:padding="7dp" > 
    </LinearLayout> 

的Java:

textView = new TextView(getContext()); 
    textView.setText("some text"); 
    textView.setTextSize(20f); 
    textView.setGravity(Gravity.CENTER); 
    textView.setTextColor(Color.BLACK); 
    textView.setTextAppearance(getContext(), android.R.style.TextAppearance_Medium); 
    addView(textView); 

但是這段文字是白色的無論我做什麼。 爲什麼?

+1

這就是答案http://stackoverflow.com/questions/6177273/textview-settextcolor-not-working – Proxytype

+0

嘗試刪除「 setTextAppearance「 –

回答

1

我確實試過了你的代碼,我想這個問題的原因是setTextAppearance。事實上,在這次電話會議後致電setTextColor()解決了問題。下面的代碼對我來說是完美的:

 TextView textView = new TextView(this); 
     textView.setText("some text"); 
     textView.setTextSize(20f); 
     textView.setGravity(Gravity.CENTER); 
     // textView.setTextColor(Color.RED); 
     textView.setTextAppearance(this, android.R.style.TextAppearance_Medium); 
     textView.setTextColor(Color.RED); 
     // setContentView(textView); 

我不知道這個問題的真正原因。

+0

謝謝,它解決了我的問題。 而不是其他解決方案,因爲我仍然在圖書館22。 – user3659739

1

使用以下設置彩色文本的編程方式:

textView.setTextColor(getResources().getColor(R.color.YOURCOLOR)); 

與支持庫23起,你必須使用下面的代碼,因爲的getColor被棄用:

textView.setTextColor(ContextCompat.getColor(context, R.color.YOURCOLOR)); 

見本:TextView setTextColor() not working

+0

謝謝,但我忘了說,我仍然在圖書館22。解決我的問題的答案是你旁邊的一個。 – user3659739

0

您可以使用:

ResourceCompact.getColor(getResources(), R.color.your_id, null); 

getResources().getColor()方法已棄用。

0

用途:用於

textView.setTextColor(Color.parseColor("#000000")); 

代替:

textView.setTextColor(Color.BLACK); 
相關問題