Android自定义控件(一)

来源:互联网 发布:知否 顾廷烨爱明兰 编辑:程序博客网 时间:2024/04/28 18:15

Android自定义控件(一)

一、自定义Button

①、定义button的选择器(一般放置于drawable文件夹下)

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <!-- 获得焦点但未按下时的背景图片 -->    <item android:drawable="@drawable/title_bar_btn_normal" android:state_enabled="true" android:state_focused="true" android:state_pressed="false"/>    <!-- 按下时的背景图片 -->    <item android:drawable="@drawable/title_bar_btn_pressed" android:state_enabled="true" android:state_pressed="true"/>    <!-- 默认时的背景图片 -->    <item android:drawable="@drawable/title_bar_btn_normal"/></selector>

②、在xml中引用,直接设置为背景即可

  <Button        android:id="@+id/btn_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_centerVertical="true"        android:layout_marginLeft="24dip"        android:background="@drawable/private_comm_backbtn_selector" />

注:Button定义后,无法保留Button按下时的背景图片(解决方式:在Button被点击后,动态的为Button设置背景即可)


二、自定义CheckBox

①、定义CheckBox选择器(一般放置于drawable文件夹下)

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/private_comm_check_box_pressed" android:state_checked="true"/><!--选中时效果-->    <item android:drawable="@drawable/private_comm_check_box_normal" android:state_checked="false"/><!--未选中时效果-->    <item android:drawable="@drawable/private_comm_check_box_normal"/></selector>

②、定义CheckBox的样式(res/values/styles.xml)

    <style name="private_comm_checkbox_style" parent="@android:style/Widget.CompoundButton.CheckBox">        <item name="android:button">@drawable/private_comm_checkbox_selector</item>    </style>

③、在layout布局中使用该样式即可

    <CheckBox        android:id="@+id/btn_check"        style="@style/private_comm_checkbox_style"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"        android:clickable="false"        android:focusable="false"        android:focusableInTouchMode="false" />

注:CheckBox同Button位于listview的Item中时会自动的抢占焦点(可以用通过设置focusable="false"来解决,一般使用时可去掉最后三行代码)


 

 

 

 

原创粉丝点击