button的点击效果学习起来事实上比较容易,此点对开发者来说也是使用的比较频繁的一个知识点,与它相关的还有编辑框的获取焦点时改变背景颜色、选择button选择时改变字体颜色等等。这些其实都是用到的drawable的seletor。
效果:(不点击时显示白色,点击时显示灰色)
实现这个效果其实很简单,在drawable中创建一个xml文件,然后输入两行代码即可解决,如图simple_button_style.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="@android:color/darker_gray"/>
<item android:drawable="@android:color/white"/>
</selector>
第一行表示点击时显示的图片,第二行表示初始状态显示的图片。
然后直接在layout文件中button的background中设置这个xml文件即可,代码如下:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button测试"
android:background="@drawable/simple_button_style"
/>
</LinearLayout>
常见问题:
在selector中设置了点击效果和初始状态效果时,点击却没有反应,错误效果以及代码如下:
这里就涉及到seletor选择图片的机制了。一旦选择到了合适的图片,那么就不会进行之后的判断了。
拿正确的代码举例来说,首先是判断button是否有被点击,如果没有,就不显示灰色,往下继续选择,然后就到了第二行,第二行提供的背景为白色,即显示白色。
在错误的代码中,第一行没有条件,即直接选择白色,跳出选择,就不会进行之后是否有被点击的判断,所以点击效果不会显示。