我在res/values下的mycolors.xml中定义了一个白色,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="my_white">#ffffffff</color>
</resources>
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我将TextView的文本颜色设置为我定义的白色:
TextView myText = (TextView) findViewById(R.id.my_text);
myText.setTextColor(R.color.my_white);
Run Code Online (Sandbox Code Playgroud)
但TextView中的文字结果是黑色.
当我在布局xml文件中使用@ color/my_white时,它工作正常.
我检查生成R.java,看看:
public static final int my_white = 0x7f070025;
我错过了什么?
谢谢.
R.color.my_white是包含对资源的引用的ID.setTextColor期望你传递一种颜色,而不是参考.代码编译并且没有错误,因为setTextColor期望int; 但是,当然,你错了int.在这种情况下,您必须将引用转换为表示该颜色的整数:
Resources res = getResources();
int color = res.getColor(R.color.my_white);
myText.setTextColor(color);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
328 次 |
| 最近记录: |