无法将颜色转换为可绘制的颜色

时间:2015-07-02 13:57:05

标签: android xml colors background render

所以我对android编程很新,我有一个我根本无法解决的问题。

我想让我的文字背景为红色,这是我在基础教程中学习的。 然而,问题是当我改变背景颜色时,我得到一个错误:

  

"渲染问题无法将红色转换为可绘制的"

这是我在activity_main中编写的代码:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView
        android:text="@string/hello_world"
        android:background="red"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

这是我的colours.xml文件:

<?xml version="1.0" encoding="utf-8"?>
    <resources>
<color name="Red">#E60000</color>
</resources>`

我甚至尝试将第10行更改为android:background="@color/red     或android:background="color/red甚至android:background="@android:color/red但似乎没有任何效果。

有人能帮我解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

有很多方法可以做到这一点......

1.创建名为Value Resource File的{​​{1}},然后在其中添加

color.xml

2.现在将您的<color name="red">#ffff0000</color> 更改为此并且应该可以正常工作。

TextView

如果你想通过代码获得那种颜色,你必须使用

<TextView
android:text="@string/hello_world"
android:background="@color/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

或者您也可以使用

声明您的颜色@DerGolem
getResources().getColor(R.color.red)

答案 1 :(得分:2)

@color/red仅在您在colors.xml文件中定义红色资源(位于res / values下)时才有效

如果您不想将颜色值输入到colors.xml文件中,请尝试将android:background的值更改为红色的十六进制值,例如#ff0000。< / p>

答案 2 :(得分:2)

添加文件colors.xml(在res / values中):

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#FF0000</color>
</resources>

`

答案 3 :(得分:2)

您的代码应该是这样的:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView
    android:text="@string/hello_world"
    android:background="@color/Red"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

由于您使用一些ressources文件来声明颜色,因此您需要添加“@ color /”以允许操作系统知道您正在引用资源文件。

然后在您的color.xml中,您将颜色命名为“Red”,但在活动文件中,您将id称为“red”,请注意Id区分大小写。所以你走在正确的轨道上,唯一的错误是在资源文件中有一个“R”,在背景颜色中有一个“r”;)

希望有所帮助

编辑:

您也可以直接使用Android的OS Color,它们可以与Id相同,只需用颜色See Doc here替换Id部分。

相关问题