分享

Android开发笔记(六)— 使用Drawable类、Color类和Resource类更改颜色

 openwudi 2010-10-08

这个范例将讲解使用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./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./apk/res/android">
  <drawable name="darkgray">#808080FF</drawable>
  <drawable name="white">#FFFFFFFF</drawable>
</resources>
main.xml
<linearlayout xmlns:android="http://schemas./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>
演示效果:
图片

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多