您的位置:首页 > 编程语言

代码中更改 TextView 文字颜色

2013-12-21 09:30 190 查看

创建工程

编写布局 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:text="TextView01"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:text="这里使用Graphics颜色静态常量"
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>


新加 drawable.xml,其中添加一个 white 颜色值

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


在代码中由 ID 获取 TextView

TextView text_A=(TextView)findViewById(R.id.TextView01);
TextView text_B=(TextView)findViewById(R.id.TextView02);


获取 Resources 对象

Resources myColor_R=getBaseContext().getResources();

获取 Drawable 对象

Drawable myColor_D=myColor_R.getDrawable(R.color.white);

设置文本背景颜色

text_A.setBackgroundDrawable(myColor_D);

利用 android.graphics.Color 的颜色静态变量来改变文本颜色

text_A.setTextColor(android.graphics.Color.GREEN);

利用 Color 的静态常量来设置文本颜色
text_B.setTextColor(Color.RED);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: