官术网_书友最值得收藏!

4.2 設置文本顏色

Color類的完整寫法是Android.Graphics.Color,它的特點是設置顏色。雖然在Android平臺上有很多種表示顏色的方法,但是類Color中提供的設置顏色方法是最好用的。在Color類中包含了如下12種最常用的顏色。

· Color.BLACK

· Color.BLUE

· Color.CYAN

· Color.DKGRAY

· Color.GRAY

· Color.GREEN

· Color.LTGRAY

· Color.MAGENTA

· Color.RED

· Color.TRANSPARENT

· Color.WHITE

· Color.YELLOW

類Color的3個靜態(tài)方法,具體說明如下。

· static int argb(int alpha, int red, int green, int blue):構造一個包含透明對象的顏色;

· static int rgb(int red, int green, int blue):構造一個標準的顏色對象;

· static int parseColor(String colorString):解析一種顏色字符串的值,比如傳入Color. BLACK。

Color類返回的都是整型結果,例如,返回0xff00ff00表示綠色、返回0xffff0000表示紅色。我們可以將這個DWORD型看做AARRGGBB,AA代表Alpha透明色,后面的就不難理解了,每一段的范圍為0~255。

實例4-1 用Color類更改文字的顏色(daima\4\yan)。

(1)設計理念

在本實例中,預先在Layout中插入了兩個TextView控件,并通過兩種程序的描述方法來實時更改原來Layout里TextView的背景色及文字顏色,最后使用類Android.Graphics.Color來更改文字的前景色。

(2)具體實現

step 1 編寫布局文件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/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"
  />
</LinearLayout>

step 2 編寫主文件yan.java,功能是調用各個公用文件來實現具體的功能。在里面分別新建了兩個類成員變量mTextView01和mTextView02,這兩個變量在onCreate之初,以findViewById方法使之初始化為Layout(main.xml)里的TextView對象。在當中使用了Resource類及Drawable類,分別創(chuàng)建了resources對象及HippoDrawable對象,調用了setBackgroundDrawable來更改mTextView01的文字底紋,并且使用setText方法來更改TextView里的文字。而在mTextView02中,使用了類Android.Graphics.Color中的顏色常數,并使用setTextColor來更改文字的前景色。文件yan.java的主要代碼如下所示。

package dfzy.yan;
import dfzy.yan.R;
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 yan extends Activity
{
  private TextView mTextView01;
  private TextView mTextView02;
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mTextView01 = (TextView) findViewById(R.id.myTextView01);
    mTextView01.setText("使用的是Drawable背景色文本。");
    Resources resources = getBaseContext().getResources();
    Drawable HippoDrawable = resources.getDrawable(R.drawable.white);
    mTextView01.setBackgroundDrawable(HippoDrawable);
    mTextView02 = (TextView) findViewById(R.id.myTextView02);
    mTextView02.setTextColor(Color.MAGENTA);
  }
}

調試運行后的效果如圖4-1所示。

圖4-1 運行效果

主站蜘蛛池模板: 太康县| 德保县| 巩留县| 托里县| 陵川县| 北海市| 梨树县| 上高县| 微山县| 尼玛县| 吉木萨尔县| 景洪市| 曲沃县| 德清县| 太仆寺旗| 新泰市| 洞头县| 衢州市| 新平| 门源| 昆明市| 开远市| 即墨市| 长汀县| 松江区| 虹口区| 西藏| 开远市| 恩施市| 宜丰县| 同德县| 正宁县| 崇信县| 安远县| 台东县| 柳州市| 晋城| 库车县| 明水县| 湟中县| 会同县|