安卓开发中Button的常见用法(总结)

按钮的基本属性就不说了,这边主要记录一下个性化按钮的样式。(比如,点击颜色变化,圆角按钮之类的)

先上效果图:

这里主要用到了StateListDrawable和shape。

PS:如果是改变控件的静态显示样式,用<shape>(可以参照之前关于TextView基本用法的那篇博文,里面有详解);如果是改变控件的状态改变的样式,用<selector>中的StateListDrawable。

StateListDrawable中可以设置的属性有:

  • drawable:引用的Drawable位图,我们可以把他放到最前面,就表示组件的正常状态~
  • state_focused:是否获得焦点
  • state_window_focused:是否获得窗口焦点
  • state_enabled:控件是否可用
  • state_checkable:控件可否被勾选,eg:checkbox
  • state_checked:控件是否被勾选
  • state_selected:控件是否被选择,针对有滚轮的情况
  • state_pressed:控件是否被按下
  • state_active:控件是否处于活动状态,eg:slidingTab
  • state_single:控件包含多个子控件时,确定是否只显示一个子控件
  • state_first:控件包含多个子控件时,确定第一个子控件是否处于显示状态
  • state_middle:控件包含多个子控件时,确定中间一个子控件是否处于显示状态
  • state_last:控件包含多个子控件时,确定最后一个子控件是否处于显示状态

实例代码如下:

style_button_colorchange.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/bbutton_danger_pressed"></item>
    <item android:drawable="@color/colorPrimary"></item>
</selector>

style_button_colorchangewithradius.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/bbutton_danger_pressed"></solid>
            <stroke android:width="1dp" android:color="@color/bbutton_danger_edge"></stroke>
            <corners
                android:topLeftRadius="5dp"
                android:topRightRadius="5dp"
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp">
            </corners>
        </shape>
    </item>

    <item android:state_enabled="false">
        <shape>
            <solid android:color="@color/bbutton_danger_disabled_edge"></solid>
            <stroke android:width="1dp" android:color="@color/bbutton_danger_disabled_edge"></stroke>
            <corners
                android:topLeftRadius="5dp"
                android:topRightRadius="5dp"
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp">
            </corners>
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="@color/colorPrimary"></solid>
            <stroke android:width="1dp" android:color="@color/colorPrimary"></stroke>
            <corners
                android:topLeftRadius="5dp"
                android:topRightRadius="5dp"
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp">
            </corners>
        </shape>
    </item>

</selector>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值