选择器(select)
当我们对一个控件,要对不同的事件,触发不同的背景.例如:我们需要对一个按钮,进行正常的状态下是一个图片,点击下去之后,又变化成另外一种图片.
步骤:
1: 要在res文件夹下面的一个drawable文件,然后建立一个xml文件.在里面定义你需要记住的状态,并且引用相应的图片
2.在控件里面使用,一般使用android:background=”@drawable/dd” (这里dd是我们自定义xml文件的文件名)
这样的方式
例如dd文件内容如下:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <!--控件未点击时的背景颜色--> <item android:state_pressed="false" android:drawable="@color/colorAccent"></item> <!--控件点击时的背景颜色--> <item android:state_pressed="true" android:drawable="@color/colorPrimaryDark"></item> </selector>
控件引用方式:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="200px" android:background="@drawable/dd" android:clickable="true" />//一定要给定控件一个初始状态 </LinearLayout>
本文介绍了Android中如何使用选择器(select)为控件设置不同状态下的背景图片。通过在drawable目录下创建XML文件定义状态并引用图片,然后在控件的背景属性中设置该XML文件,可以实现按钮等控件在正常和点击状态下的图片切换效果。
130

被折叠的 条评论
为什么被折叠?



