android 自定义图形之层叠样式 [layer-list] 的使用

     通过使用层叠样式  layer-list  可以将多张图像层叠在一起   形成一张新的图像.
在第一次接触, 是为了解决一个LinearLayout 中包含一个Button ,当点击该LinearLayout和Button 多要改变LinearLayout的背景色. 由于Button无法获取焦点改变事件(OnFocusChangeListener), 而设置Button点击事件我们也只能扑捉按钮的一瞬间, 所以我们还的扑捉手势动作(GestureDetector)  . 而且这些多要代码去控制,

听说 ImageButton能解决Button的这一弱点哦..

下面是效果图





接下来发的是drawable xml图像文件

1. 默认的图片布局 : layer_main_button_life_n.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:drawable="@drawable/login_btn_normal" />
    <item android:drawable="@drawable/main_icon_life" 
        android:left="20dip"
        android:right="150.0dip"
        android:top="8dip"
        android:bottom="8dip"/>

</layer-list>


2. 按下 或者有焦点的图像布局:layer_main_button_life_p.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item android:drawable="@drawable/login_btn_focus" />
    <item android:drawable="@drawable/main_icon_life" 
        android:left="20dip"
        android:right="150.0dip"
        android:top="8dip"
        android:bottom="8dip"/>

</layer-list>


3. 为新的图像创建一个选择器布局 :selector_main_button_life.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/layer_main_button_life_p" android:state_pressed="true"/>
    <item android:drawable="@drawable/layer_main_button_life_p" android:state_selected="true"/>
    <item android:drawable="@drawable/layer_main_button_life_n"/>

</selector>


4. 最后在布局文件中 main.xml中的Button直接引用该选择器就OK了
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
	<Button 
	    android:layout_centerInParent="true"
	    android:layout_width="wrap_content"
	    android:layout_height="50dp"
	    android:background="@drawable/selector_main_button_life"
	    android:paddingLeft="100dip"
	    android:text=" 生 活 资 讯 "
	    android:textSize="20sp"/>
    
</RelativeLayout>



注: layer-list 对应的Java类为LayerDrawable  ,大家也可能使用该类在类中创建自己的图像

猜你喜欢

转载自evog.iteye.com/blog/2036841