Android从java代码设置文本视图颜色

Pra*_*ham 15 android android-layout

我有一个列表,我为此编写了一个自定义适配器.我想为此设置一些文本颜色(例如橙色代码#F06D2F).我正在为我的getView()方法提供代码片段.

TextView text = new TextView(this.context);
// text.setPadding(25, 5, 0, 0);

text.setBackgroundResource(R.drawable.back_horizontal);

// text.setClickable(false);
// text.setFocusable(false);
text.setEllipsize(TruncateAt.END);
text.setSingleLine(true);

// text.setTextColor(R.color.yellow);

text.setTextColor(R.color.Orange);
text.setGravity(Gravity.CENTER_VERTICAL);


helvetica_normal = Typeface.createFromAsset(context.getAssets(), "fonts/helvetica.ttf");

text.setTypeface(helvetica_normal);
// text.setTextColor(R.color.yellow);



text.setText(objects[position]);

LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
manager.addView(text, layoutParams);
Run Code Online (Sandbox Code Playgroud)

问题是我看不到颜色设置为橙色.什么地方出了错?

注意:上下文在构造函数和对象(字符串数组)中传递

谢谢你的帮助

San*_*esh 54

尝试这样,以下工作对我来说很好

textview.setTextColor(this.getResources().getColor(R.color.orange));
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用this.getResources().getColor().最好使用ContextCompat.getColor(). (4认同)
  • 这里的关键是上面的fredley评论 - 如果你定义一个没有不透明度的颜色,那么它就会失败.该解决方案偶然实现了这种或多或少.如果Presham刚刚为他原来的颜色定义添加了不透明度,他的原始代码也会起作用. (2认同)

Ani*_*tel 19

text.setTextColor(Color.parseColor("#FFFFFF"));
Run Code Online (Sandbox Code Playgroud)


Vin*_*ins 8

你也可以使用 text.setTextColor(0xFFF06D2F);
但不仅仅是 text.setTextColor(0xF06D2F);


Rai*_*975 5

这对我有用,而且很简单。首先,导入“颜色”

import android.graphics.Color;
Run Code Online (Sandbox Code Playgroud)

那么你所要做的就是:

text.setTextColor(Color.RED);
Run Code Online (Sandbox Code Playgroud)

今天才发现这一点(2013 年 9 月 20 日)。您可以继续声明一个变量,如下所示:

private final int ORANGE = 0xFFFF3300;
Run Code Online (Sandbox Code Playgroud)

那么你所要做的就是:

text.setTextColor(ORANGE);
Run Code Online (Sandbox Code Playgroud)

请注意,前两个十六进制字符用于不透明度(“FF”表示不透明)。然后,在上面的示例中,第二个“FF”代表红色,然后“33”代表绿色,“00”代表蓝色。这样应该可以创造出很多颜色。

我对 Android 编程还很陌生——这是我在这个论坛上发表的第一篇文章。感谢大家的贡献!