Android:实现按钮点击后高亮的效果

未点击前:

点击后:

可以看出点击后,颜色变得更加高亮了(你也可以设置为别的颜色,效果更加明显)

由于我们很多按钮都需要这种样式,所以我们把这种按钮的样式放在styles.xml中,方便重复使用

第一步:在res/drawable文件夹下定义两种不同状态下的按钮的形状

在文件夹上鼠标右键—>new drawable resource file—>RootElement选择Shape

btn_n.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!--设置整个按钮颜色-->
    <solid android:color="#D43433"></solid>
    <!--设置边角弧度-->
    <corners android:radius="4dp"></corners>
</shape>

btn_h.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#C80F1F"></solid>
    <corners android:radius="4dp"></corners>
</shape>

这两个xml主要的不同就在于btn_h.xml的color更高亮一点

第二步:在res/drawable文件夹下定义selector,来确定在哪些状态下使用什么drawable

在文件夹上鼠标右键—>new drawable resource file—>RootElement选择Selector
btn_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!--View高亮状态-->
    <!--
         state_focused:如果在对象具有输入焦点(例如当用户选择文本输入时)时应使用此项目
         state_pressed:如果在按下对象(例如触摸/点按某按钮)时应使用此项目
         state_selected:如果在使用定向控件浏览(例如使用方向键浏览列表)的情况下,对象为当前用户选择时应使用此项目
    -->
    state_pressed:
    <item android:drawable="@drawable/btn_h" android:state_focused="true"></item>
    <item android:drawable="@drawable/btn_h" android:state_pressed="true"></item>
    <item android:drawable="@drawable/btn_h" android:state_selected="true"></item>
    <!--View普通状态-->
    <item android:drawable="@drawable/btn_n"></item>
</selector>
第三步:在values/styles.xml中定义按钮具体的样式,并将backgroud设置为我们上一步定义的selector

styles.xml

 <!--自定义按钮-->
    <style name="btn_submit">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/btnHeight</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">@dimen/textSize</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_marginLeft">@dimen/marginSize</item>
        <item name="android:layout_marginRight">@dimen/marginSize</item>
        <item name="android:background">@drawable/btn_selector</item>
    </style>
第四步:在layout文件中通过style调用就行了
    <Button
        style="@style/btn_submit"
        android:layout_marginTop="@dimen/marginSize"
        android:text="登 录" />
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Selenium399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值