Android使用selector自定义按钮
可视化编辑器,alt+1到9键,切换到工具区,tab键,选择按钮,esc键,返回编辑
Android使用selector自定义按钮
以前定义按钮的时候,想使用自定义的Button总是习惯在activity中获取该按钮然后,重写该按钮的onTouchListener然后在当中切换按钮的背景图片。这样做不但使activity中的代码变得臃肿而且不能该按钮不能达到重用的目的。
后来接触到了Android 中的selector挺好用的,下面详细讲解一下如何使用selector,首先在res\drawable文件夹下创建一个xml文件如图:
再在drawable文件中添加你想应用在按钮上的图片,包括按下的图片和不按时的图片。
然后在该文件中添加:drawable
<?xmlversion="1.0"encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><!--当按钮获得焦点时定义显示的图片--><itemandroid:state_focused="true"android:drawable="@drawable/p_w_picpath_btn_down"/><!--当按钮被选中时定义现实的图片--><itemandroid:state_selected="true"android:drawable="@drawable/p_w_picpath_btn_down"/><!--当按钮被点击时定义显示的图片--><itemandroid:state_pressed="true"android:drawable="@drawable/p_w_picpath_btn_down"/><!--默认按钮没有被选中时显示的图片--><itemandroid:drawable="@drawable/p_w_picpath_btn_up"/></selector>
该文件名字叫做button_selector.xml,完成之后,把你想应用的按钮的drawable属性改为@drawable/button_selector就可以了 如下:
<Buttonandroid:id="@+id/button_add"android:layout_width="115dp"android:layout_height="wrap_content"android:layout_margin="5px"android:layout_weight="1"android:background="@drawable/button_selector"android:text="自定义按钮"/>
开发微博推荐: http://crh.chinacloudsites.cn/
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。