1、自定义Button
一直习惯了用系统自带的android Button控件,从来都没有想过这些控件的实现过程,在网上看到了一篇自定义控件的文章,学习了一下,感觉有所理解,现在做一个总结。
①不管是什么元素控件都是包含两个部分,界面布局和响应事件及操作。按键的响应事件就不总结了,和系统的一样,也可以自定义。重点总结一些界面的布局。对于Button的界面分为多种,列举正常和单击效果。
②引用自定义Button,自定义的界面主要是通过background设置的,可以直接设置为图片资源,也可以设置为selector(对元素的不同操作显示不同的界面)资源。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyButtonActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@drawable/selector_btn"
android:text="@string/hello_world" />
</RelativeLayout>
②创建selsector资源来处理不同的界面效果,根据selsector中的属性来决定元素适应环境的显示效果。在此引用的drawable资源可以是图片资源也可以是其他的图形,等等资源。创建selector_btn.xml资源。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/shape_btn_down" android:state_pressed="true"></item>被按下
<item android:drawable="@drawable/shape_btn_up" android:state_pressed="false"/>没被按下
<item android:drawable="@drawable/shape_btn_up" android:state_window_focused="false"></item>
</selector>
③模仿系统自带的BUTTON效果,用自定drawable图形的方式实现。创建shape_btn_down.xml和shape_btn_up.xml资源。
shape_btn_up
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#00000000" />
<stroke
android:width="1dp"
android:color="#Ebebeb" />
<corners android:radius="10dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
shape_btn_down
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
>
<stroke
android:width="1dp"
android:color="#EBEBEB" />
<corners android:radius="10dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
<gradient android:startColor="#BFEEFF"
android:endColor="#40B9FF"
android:angle="270"/>
</shape>
效果:
点击前
点击后