android settextcolor 引用xml,关于android:TextView setTextColor()无效

我以编程方式创建这样的元素的列表(没有ListView,只是将它们添加到父级):

android:orientation="vertical" android:layout_weight="1">

android:layout_width="fill_parent" android:layout_height="wrap_content"/>

android:layout_width="fill_parent" android:layout_height="wrap_content"

android:textSize="10sp" android:textColor="@color/red"/>

另外,我在values / colors.xml中定义了一些颜色。 如您所见,ID为"lagerstand_text"的TextView默认将其颜色设置为红色。 这样可行。

用Java创建元素时,我做到了

lagerstandText.setText("bla");

对于某些元素,我也这样做

lagerstandText.setTextColor(R.color.red);

和其他颜色。 虽然我没有调用setTextColor()的元素是红色的,但是所有其他元素都是灰色的,无论我选择哪种颜色(即使它再次是相同的红色)。

这是为什么?

如果我的回答对您有帮助,您可以接受答案

文档对此并不是很冗长,但在调用setTextColor时不能只使用R.color整数。您需要调用getResources().getColor(R.color.YOURCOLOR)来正确设置颜色。

使用以下命令以编程方式设置文本的颜色:

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

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

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

好的,那很有效。在这种情况下,API文档可能会更冗长......

你也可以用Color。 (这里是红绿黑蓝黄等)setTextColor(Color.RED)

感谢您的信息......但是这个getResources()让我传递了一系列上下文。应该有一些更好的方式来访问全球资源。

@Umair在Application类上使用静态变量。

@Kontinuity,我读到保持静态变量的上下文是内存泄漏的重要来源。

@Umair stackoverflow.com/questions/2002288/…

如果我使用R.color.green,它会为我工作。但如果我使用android.R.color.white不工作。知道为什么吗?

getColor(R.color.YOURCOLOR)已在第23版中弃用。请参阅此链接以了解新方法

因此,有很多方法可以完成这项任务。

1。

int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;

textview.setTextColor(color);

2。

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

3。

textView.setTextColor(0xffbdbdbd);

4。

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

5。

textView.setTextColor(Color.argb(a_int, r_int, g_int, b_int));

有没有办法找出特定的颜色值是否会使文本消失?

@ChristopherMasser不明白你想说什么???

我在使用setTextColor(颜色)之前调整颜色的亮度。在一些未知的情况下,TextView只会在设备上消失(独立于背景)。我想编写一个测试函数来检查在使用setTextColor(color)之前"color"是否是有效的颜色值。

@ChristopherMasser没有尝试任何你说的话?

1.标准颜色你喜欢请跟下面。

textview.setTextColor(Color.select_color)

2.想要使用custwom颜色将其添加到color.xml文件中

textview.setTextColor(getResources().getColor(R.color.textbody));

要么

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

要么

subText.setTextColor(Color.rgb(255,192,0));

为了将来参考,您可以使用以下内容:

String color = getString(Integer.parseInt(String.valueOf(R.color.my_color)));

my_textView.setTextColor(Color.parseColor(color));

这样您就可以使用颜色资源。

R类中定义的特定颜色(在xml布局中定义)的整数id不能作为参数传递给View类的setTextColor()方法。

您必须通过以下代码行获取setTextColor()的参数:

int para=getResources().getColor(R.color.your_color,null);

view.setTextColor(para,null);

方法getColor(int id)已经过折旧...而是使用上面代码行中的getColor(int id,Resources.Theme theme)。

The `second parameter( theme )` can be null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值