Android 设置Button按下的效果

来源:互联网 发布:网络段子集锦 编辑:程序博客网 时间:2024/06/05 14:14

在平常的开发中,Button是经常使用到的控件之一,在系统默认情况下,按钮点击是没有任何效果的,这样就会导致用户不确定有没有点击到按钮,从而多次点击,那么如何设置按钮按下时的状态效果呢?其实很简单;
这里写图片描述
老样子,先看一下效果:
这里写图片描述
接下来介绍一下实现的方法:
首先在drawable文件夹下创建selector.xml文件:
就两行代码,分别代表button选中和未选中这两种状态,这两种状态又分别对应两种不同的效果,点击时按钮背景是黄色的,松开按钮,背景为绿色;

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

两种不同的样式分别对应的xml文件:
选中状态:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="#ffff00"/>    <stroke android:width="0.7dp" android:color="#87cdff"/>    <corners android:radius="4dp"/></shape>

未选中状态:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <solid android:color="#0ef200"/>    <stroke android:width="0.7dp" android:color="#87cdff"/>    <corners android:radius="4dp"/></shape>

如果不是项目的需要,其实不用写的这么麻烦,我只是顺便加一下shape的用法,同样是在drawable文件夹下创建shape.xml,里面对应的属性分别是:
solid:背景颜色
stroke:描边粗细、颜色
corners:圆角弧度
最后在main_activity.xml中通过drawable引用刚才写好的select.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_centerVertical="true"        //看我看我,我在这里!!!        android:background="@drawable/button_select"        android:text="button按下效果" /></RelativeLayout>

看吧,是不是很简单呀!

0 0
原创粉丝点击