Android自定义控件(一)

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"来解决,一般使用时可去掉最后三行代码)


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值