您的位置:首页 > 其它

更改TextView文字颜色-------引用Drawable颜色常数及背景色

2010-12-14 11:42 761 查看
上一个例子通过Drawable 来定义颜色常数,但实际设计中最常用的方法,则是使用程序控制TextView或者其他对象的背景色(setBackgroundDrawable方法),如判断对象被点击时的背景色亮起、当失去焦点时,又恢复成原来的背景色等等。

下面的例子中,预先在Layout当中设计好两个TextView,并在onCreate同时,通过两中程序表述方法,实时更改原来Layout里TextViewd的背景色以及文件颜色,最后学习使用Android默认的颜色常数(graphics.Color)来更改文件的前景色。

运行结果



程序

1、ex03_04/res/values/ 下创建color.xml文件,如下:

<?xml version="1.0" encoding="utf-8"?>

<resources>
<drawable name="gray">#808080FF </drawable>
<drawable name="white">#FFFFFFFF</drawable>
</resources>

2、ex03_04/res/layout/main.xml

文件里预先定义两个TextView

<?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:id="@+id/widget28"
android:layout_marginLeft="0px"
android:layout_marginTop="0px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/widget29"
android:layout_marginLeft="0px"
android:layout_marginTop="10px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

3、ex03_04/src/irdc.ex03_04/ex03_04.java

程序里新建两个类成员变量:mTextView01与mTextView02,这两个变量在onCreate之初,以findViewById方法使之初始化为layout(mian.xml)里的TextView对象。在当中使用了 Resource类以及Drawable类,分别创建了resources对象以及HippoDrawable对象,并将创建的R.drawable.white以getDrawable方法加载,最后则调用了setBackgroundDrawable来更改mTextView01的文字底色,用setTextColor更改文字的颜色。使用setText更改TextView里的文字。

在mTextView02中使用graphics.Color里的颜色常数,接着,再利用setTextColor更改文字的前景色。

package com.example.ex03_04;

import android.app.Activity;
import android.os.Bundle;

// add by christina 20101214 start
//引用类
import android.widget.TextView;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
//add by christina 20101214 end

public class ex03_04 extends Activity {
//add by christina 20101214 start
private TextView mTextView01;
private TextView mTextView02;
//add by christina 20101214 end
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//add by christina 20101214 start
mTextView01=(TextView)findViewById(R.id.widget28);
mTextView01.setText("我是应用Drawable背景色的戴维文本。");

/*用Drawable的方法来改变文本的背景和前景色*/
Resources resources=getBaseContext().getResources();
Drawable HippoDrawable=resources.getDrawable(R.drawable.white);
mTextView01.setBackgroundDrawable(HippoDrawable);
mTextView01.setTextColor(R.drawable.gray);

mTextView02=(TextView)findViewById(R.id.widget29);
/*下面使用Color.MANENTA指定文本的颜色为紫红色*/
mTextView02.setTextColor(Color.MAGENTA);
//add by christina 20101214 end
}
}

扩展学习:

在程序中使用了Color.MANGENTA让TextView里的文字变成粉红色,实际上,在Android里还定义了一下12种常见的颜色:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: