HTML/JavaScript小工具

HTML/JavaScript小工具

2012年9月22日 星期六

Android 使用StateListDrawablec換樣式

StateListDrawable可以根据View的不同状态,更换不同的背景

可以应用如EditText,Button等中,以Button为例

系统中默认的按钮被按下的颜色和未点击时的颜色不一样,该种实现可以用Java代码和XML实现

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

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

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

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

android:variablePadding=["true" | "false"] >

<item

android:drawable="@[package:]drawable/drawable_resource"

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>


下面对应的具体实例,由于是做背景用,该xml将放于/res/drawable下面
StateList中第一个匹配当前状态的item会被使用。因此,如果第一个item没有任何状态特性的话,那么它将每次都被使用,这也是为什么默认的值必须总是在最后
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/btn_selected"/>
    <item android:state_focused="true" android:drawable="@drawable/btn_selected"/>
    <item android:state_enabled="true" android:drawable="@drawable/btn_normal"/>
    <item  android:drawable="@drawable/btn_normal" />
</selector>

在Button的xml中进行加载:
 <Button
            android:id="@+id/canel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/btn_cancel"
            android:layout_margin="10dip"
            android:layout_weight="1"
            android:textColor="#ffffffff"
            android:textSize="15sp"
            android:background="@drawable/button_drawable"
            />