Sean's Note: 5月 2015

2015年5月13日 星期三

Using StateListDrawable

想要在 View 上呈現 Click 的效果(顏色的變化),用 XML 來實作,只要在 drawable
檔裡定義 selector 屬性,然後將該 drawable 設給該 View 的 android:background
即可。範例如下:
  
// color_selector_view_bg
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:state_pressed="true"
        android:drawable="@color/grey"
         >
    </item>
    <item 
     android:drawable="@color/white"
         >
    </item>
</selector>
  
<view>
  android:id="@+id/view_header" 
  android:layout_height="wrap_content" 
  android:layout_width="wrap_content">
  android:background="@drawable/color_selector_view_bg"
</view>

但想要用程式碼來實作的話,就稍微麻煩一些些,得用到 StateListDrawable 這個類別,
來設定個別狀態所對應的 drawable。加入的順序不同,行為也不同,越廣義的狀態要
晚加入,例如 state_enabled 就應該要最後加入。
以下是範例:
  
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(colorGrey));
stateListDrawable.addState(new int[]{android.R.attr.state_selected}, new ColorDrawable(colorWhite));
stateListDrawable.addState(new int[]{android.R.attr.state_enabled}, new ColorDrawable(colorwhite));
view.setBackground(stateListDrawable);

另外要注意,每個 view 不能共用 StateListDrawable,尤其是應用在 ListView 和
GridView 上,否則按下 A view,B view 也跟者改變了。

Show error on EditText to inform user

現在才發現原來 EditText 有個 showError() 的方法,

可以提示使用者輸入錯誤或未輸入的提示。

Ref: http://www.technotalkative.com/android-show-error-in-edittext/