6.9.2. 设置颜色

优质
小牛编辑
120浏览
2023-12-01

6.9.2.设置颜色

现在界面有了背景图,但是文本框呢?依然乏善可陈。接下来为它设置下颜色,同时添加透明效果。

Android使用标准的RGB颜色,加上可选的Alpha项,你可以使用RGB或ARGB两种方式描述颜色。其中A表示透明度,R表示红色,G表示绿色,B表示蓝色。每个值都在0~255之间,通过它们的混合,即可调和出各种不同的颜色以及不同的透明度。颜色的数目是有限的,这一点可能会让莫奈这样的大画家不高兴,但对电子设备来说,这已经绰绰有余了。

0到255之间的值,换成十六进制就是0到FF。表示颜色的话,一般还是十六进制用的多。格式是AARRGGBB,其中的每个字符都是0到F之间的数字。这一格式有一种简化形式,那就是ARGB,其中每个字符表示重复的两个字符。比如#3A9F与#33AA99FF相同,对应的Alpha为#33、红为#AA、绿为#99、蓝为#FF。可以留意这里的#号,它用来表示这是个十六进制数,与十进制做区别。

好,更新EditText的background属性为#cfff,表示背景色为半透明的白色。

也可以修改textColor属性更改TextView的文本颜色。比如我们觉得白色不错,可以把它设置为#fff,也可以输入@android:color/white引用操作系统内置的资源定义,也就是白色。

例 6.8. res/layout/status.xml

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

<!-- Main Layout of Status Activity -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" android:background="@drawable/background"><!-- -->

<!-- Title TextView-->

<TextView android:layout_width="fill_parent"

android:layout_height="wrap_content" android:gravity="center"

android:text="@string/titleStatus" android:textSize="30sp"

android:layout_margin="10dp" android:textColor="@android:color/white" /><!-- -->

<!-- Text Counter TextView -->

<TextView android:layout_width="wrap_content"

android:layout_height="wrap_content" android:layout_gravity="right"

android:id="@+id/textCount" android:text="000"

android:layout_marginRight="10dp" />

<!-- Status EditText -->

<EditText android:layout_width="fill_parent"

android:layout_height="fill_parent" android:layout_weight="1"

android:hint="@string/hintText" android:id="@+id/editText"

android:gravity="top|center_horizontal" android:background="#cfff" /><!-- -->

<!-- Update Button -->

<Button android:layout_width="fill_parent"

android:layout_height="wrap_content" android:text="@string/buttonUpdate"

android:textSize="20sp" android:id="@+id/buttonUpdate" />

</LinearLayout>

  1. 设置主布局的背景为/res/drawable/目录下的background.png。
  2. 设置标题文本的颜色为系统资源定义中的白色。
  3. 设置文本框的背景为透明白色,十六进制格式,也就是#cfff。

到这里,我们已观察了设置View颜色的几种方法。Android为开发者提供了丰富的控件,它们的属性也数目繁多、功能各异,但道理都是相同的。要设置哪个控件的哪个属性,我们完全可以凭经验推断出来,这就是最小立异原则的一种体现。