天天看點

Android-----使用Button特效selector+shape

如果對系統的ui效果不滿意,可以用shape進行自定義

當然除了使用drawable這樣的圖檔外今天談下自定義圖形shape的方法,對于button控件android上支援以下幾種屬性shape、gradient、stroke、corners等。

我們就以目前系統的button的selector為例說下:

對于上面,這條shape的定義,分别為漸變,在gradient中startcolor屬性為開始的顔色,endcolor為漸變結束的顔色,下面的angle是角度。接下來是stroke可以了解為邊緣,corners為拐角這裡radius屬性為半徑,最後是相對位置屬性padding。

對于一個button完整的定義可以為:

注意!提示大家,以上幾個item的差別主要是展現在state_pressed按下或state_focused獲得焦點時,當當來判斷顯示什麼類型,而沒有state_xxx屬性的item可以看作是正常狀态下。

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

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

<item

android:color="hex_color"

android:state_pressed=["true" | "false"]

android:state_focused=["true" | "false"]

android:state_selected=["true" | "false"]

android:state_active=["true" | "false"]

android:state_checkable=["true" | "false"]

android:state_checked=["true" | "false"]

android:state_enabled=["true" | "false"]

android:state_window_focused=["true" | "false"] />

</selector>

elements:

<selector>

必須。必須是根元素。包含一個或多個<item>元素。

attributes:

xmlns:android

string,必須。定義xml的命名空間,必須是

“http://schemas.android.com/apk/res/android”.

<item>

定義特定狀态的color,通過它的特性指定。必須是<selector>的子元素。

android:color

16進制顔色。必須。這個顔色由rgb值指定,可帶alpha。

這個值必須以“#”開頭,後面跟随alpha-red-green-blue資訊:

l #rgb

l #argb

l #rrggbb

l #aarrggbb

android:state_pressed

boolean。“true”表示按下狀态使用(例如按鈕按下);“false”表示非按下狀态使用。

android:state_focused

boolean。“true”表示聚焦狀态使用(例如使用滾動球/d-pad聚焦button);“false”表示非聚焦狀态使用。

android:state_selected

boolean。“true”表示選中狀态使用(例如tab打開);“false”表示非選中狀态使用。

android:state_checkable

boolean。“true”表示可勾選狀态時使用;“false”表示非可勾選狀态使用。(隻對能切換可勾選—非可勾選的構件有用。)

android:state_checked

boolean。“true”表示勾選狀态使用;“false”表示非勾選狀态使用。

android:state_enabled

boolean。“true”表示可用狀态使用(能接收觸摸/點選事件);“false”表示不可用狀态使用。

android:window_focused

boolean。“true”表示應用程式視窗有焦點時使用(應用程式在前台);“false”表示無焦點時使用(例如notification欄拉下或對話框顯示)。

注意:記住一點,statelist中第一個比對目前狀态的item會被使用。是以,如果第一個item沒有任何狀态特性的話,那麼它将每次都被使用,這也是為什麼預設的值必須總是在最後(如下面的例子所示)。

examples:

xml檔案儲存在res/color/button_text.xml

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

<item android:state_pressed="true"

android:color="#ffff0000"/> <!-- pressed -->

<item android:state_focused="true"

android:color="#ff0000ff"/> <!-- focused -->

<item android:color="#ff000000"/> <!-- default -->

這個layout xml會應用colorstatelist到一個view上:

<button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/button_text"

android:textcolor="@color/button_text" />

繼續閱讀