【问题标题】:programmatically setTextColor in TextView in library 22 in Android以编程方式在 Android 的库 22 中的 TextView 中设置TextColor
【发布时间】:2016-09-27 17:51:01
【问题描述】:

最近我更改了一些应用程序,但由于我不理解“setTextColor”方法的原因,它似乎不再有效。

在我的 XML 中,我有一个列表视图,并以编程方式在此列表视图中添加 TextView。

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);

但是无论我做什么,这个文本都是白色的。 为什么?

【问题讨论】:

标签: android colors textview


【解决方案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);

我不知道这个问题的真正原因。

【讨论】:

  • 谢谢,它解决了我的问题。而不是其他解决方案,因为我还在图书馆 22。
【解决方案2】:

使用以下代码以编程方式设置文本颜色:

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

从支持库 23 开始,您必须使用以下代码,因为不推荐使用 getColor:

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

看到这个:TextView setTextColor() not working

【讨论】:

  • 谢谢,但我忘了说我还在 22 号图书馆。解决我问题的答案就在你旁边。
【解决方案3】:

用途:

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

代替:

textView.setTextColor(Color.BLACK);

【讨论】:

    【解决方案4】:

    你可以使用:

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

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

    【讨论】:

      猜你喜欢
      • 2011-12-16
      • 2011-01-28
      • 1970-01-01
      • 2011-03-09
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多