您的位置:首页 > 移动开发 > Android开发

Android btn在不同点击状态下的不同表现

2019-08-07 10:29 53 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/u014714188/article/details/98728481

Android btn在不同点击状态下的不同表现

在默认情况下,btn在焦点的移入移出,点击等等,btn样式是没有变化的。本文通过简单的方法,实现btn不同状态下的样式改变。

首先,先来看看最后的效果

由于无法通过短视频的方式展示,我只能通过文字描述下。下图是默认情况下btn的显示。当我们获取到焦点或点击的时候,会btn下面会出现阴影且btn会缩小下。

实现btn默认样式

在drawable下新建xml样式文件btn_commit_default,具体实现如下:

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

<!--实体颜色,按需求自己定义,我的是#2d86b8-->
<solid android:color="@color/colorMain"></solid>

<!--弧度,按需求自己定义,我的是5dp-->
<corners android:radius="@dimen/btnRadius"></corners>

</shape>

实现btn高亮样式(由于项目需求,我这里点击时候的样式并没有改变)

在drawable下新建xml样式文件btn_commit_high_light,具体实现如下:

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

<!--实体颜色,按需求自己定义,我的是#2d86b8-->
<solid android:color="@color/mainColorH"></solid>

<!--弧度,按需求自己定义,我的是5dp-->
<corners android:radius="@dimen/btnRadius"></corners>

</shape>

我们再写一个xml来集成上面的两种样式

在drawable下新建xml样式文件btn_commit_select,具体实现如下:

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

<!--View 高亮,这里就是执行的各个状态,获取焦点,点击后,移出移入等等,按需求自己定义xml-->
<item android:state_focused="true" android:drawable="@drawable/btn_commit_high_light"></item>
<item android:state_pressed="true" android:drawable="@drawable/btn_commit_high_light"></item>
<item android:state_selected="true" android:drawable="@drawable/btn_commit_high_light"></item>

<!--View 默认,默认显示下的btn-->
<item android:drawable="@drawable/btn_commit_default"></item>
</selector>

最后使用

我们上面的btn_commit_select样式怎么放入到btn上面呢?很简单,直接作为背景引用即可,无需我们手动的写事件去监听再改变样式。

<!--登录按钮-->
<style name="commitBtn">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/btnHeight</item>
<item name="android:layout_marginLeft">@dimen/marginSize</item>
<item name="android:layout_marginRight">@dimen/marginSize</item>
<item name="android:gravity">center</item>
<item name="android:textSize">@dimen/titleSize</item>
<item name="android:textColor">@color/white</item>
<item name="android:background">@drawable/btn_commit_select</item>
</style>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: