這個范例將講解使用Drawable類和Resource類更改顏色,并且講解使用Color類下的常量。
設計思路:
1、首先我們需要在main.xml布局文件建立兩個TextView控件,分別把id命名為myTextView01和myTextView01。
2、在\res\values\color.xml下增加兩個drawable標簽,分別命名為darkgray和white,值為#808080FF和#FFFFFFFF。
3、在\res\values\string.xml下增加兩個string標簽,分別命名為str_textview01和str_textview02,值為Drawable和graphics.Color。
4、在EX03_03.java文件里使用findViewById()方法取得在main.xml里面兩個TextView控件。并且命名為mTextView01和mTextView02。(1)對mTextView01操作。先要取得Resource類型的對象,使用getBaseContext().getResources()。然后對剛才取得的Resource對象使用getDrawable(R.drawable.white)方法,取得Drawable類型的對象。對myTextView01.setBackgroundDrawable()傳入剛才取得的Drawable對象。(2)對mTextView02操作,使用setTextColor(Color.MAGENTA)把字體顏色設置成紫紅色,再通過藍顏色的值-16777216,使用setBackgroundColor(-16776961)設置背景顏色。
源代碼:
EX03_03.java
package dan.ex03_03;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.TextView;
public class EX03_03 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//TextView使用Drawable對象設置背景色
TextView mTextView01 = (TextView) findViewById(R.id.myTextView01);
Resources resource = getBaseContext().getResources();
Drawable hippoDrawable = resource.getDrawable(R.drawable.white);
mTextView01.setBackgroundDrawable(hippoDrawable);
//使用Color.MAGENTA指定文本顏色為紫色
TextView mTextView02 = (TextView) findViewById(R.id.myTextView02);
mTextView02.setTextColor(Color.MAGENTA);
mTextView02.setBackgroundColor(-16776961);
}
}
string.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<string name="hello">Hello World, EX03_03!</string>
<string name="app_name">EX03_03</string>
<string name="str_textview01">Drawable</string>
<string name="str_textview02">graphics.Color</string>
</resources>
color.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<drawable name="darkgray">#808080FF</drawable>
<drawable name="white">#FFFFFFFF</drawable>
</resources>
main.xml
<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/myTextView01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/str_textview01">
<textview android:id="@+id/myTextView02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/str_textview02">
</textview>
</textview>
</linearlayout>
演示效果: