2016-09-27 57 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); 
相关问题