歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發中顏色的使用

Android開發中顏色的使用

日期:2017/3/1 11:11:34   编辑:Linux編程

Android 開發中使用的顏色可以分為兩種,自定義顏色和系統顏色

1.自定義顏色:

顏色值的定義是通過RGB三原色和一個alpha值來定義的(加色原理)。以井號(#)開始,後面是Alpha-Red-Green-Blue的格式。
形如:
#RGB
#ARGB
#RRGGBB
#AARRGGBB

通常使用#RRGGBB 或者#AARRGGBB的形式

1.1 在資源文件中定義顏色:
一般在res\values下建立colors.xml文件,定義顏色,如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resourses>
  3. <color name="red">#ff0000</color>
  4. </resourses>
1.2 顏色的使用

1.2.1 在代碼中使用顏色
R.color.color_name
例如:

  1. Button btn1 = (Button) findViewById(R.id.button1);
  2. int color = Resources.getSystem().getColor(R.color.red);
  3. btn1.setBackgroundColor(color);


1.2.2 在布局文件中使用顏色
@[package:]color/color_name
例如:

  1. <Button
  2. android:id="@+id/button1"
  3. android:layout_height="wrap_content"
  4. android:layout_width="match_parent"
  5. android:text="Address book"
  6. android:background="@color/red"
  7. ></Button>
這個地方也可以直接使用顏色值,但是不推薦這樣做
  1. <pre name="code" class="java"><blockquote style="margin:0 0 0 40px; border:none; padding:0px"><pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); "><Button
  2. android:id="@+id/button1"
  3. android:layout_height="wrap_content"
  4. android:layout_width="match_parent"
  5. android:text="Address book"
  6. android:background="#ff0000"
  7. ></Button>

2.系統顏色
android也有一些內置的顏色,例如系統資源中定義的顏色,十分有限。
android.graphics.Color類中也提供了一些顏色常量和構造顏色值的靜態方法。

2.1 系統顏色的使用
2.1.1 在代碼中使用系統顏色

系統資源中定義的顏色值十分有限
Button btn1 = (Button) findViewById(R.id.button1);

  1. int color = Resources.getSystem().getColor(android.R.color.background_dark);
  2. btn1.setBackgroundColor(color);
Color類中的顏色常量
  1. Button btn1 = (Button) findViewById(R.id.button1);
  2. btn1.setBackgroundColor(Color.CYAN);
使用Color類中的靜態方法
  1. Button btn1 = (Button) findViewById(R.id.button1);
  2. btn1.setBackgroundColor(Color.argb(0xff, 0xff, 0x00, 0x00));
2.1.2 在布局文件中使用系統顏色
  1. <Button
  2. android:id="@+id/button1"
  3. android:layout_height="wrap_content"
  4. android:layout_width="match_parent"
  5. android:text="Address book"
  6. android:background="@android:color/background_dark"
  7. ></Button>
Copyright © Linux教程網 All Rights Reserved