selector实现点击图片切换(解决常见的点击无效有关问题)

selector实现点击图片切换(解决常见的点击无效问题)

实现效果图:

selector实现点击图片切换(解决常见的点击无效有关问题)     selector实现点击图片切换(解决常见的点击无效有关问题)

         图片未点击前                         图片点击后

selector的实现方法其实很简单,只需3步:

第一步:选择两张图片效果图放在res/drawable-hdpi中,放在mdpi也可以

第二步:在mdpi文件夹中新建xml文件,命名为selector.xml。注意名字selector后面会引用到。

在selector.xml文件中,完成代码:

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

    <item android:drawable="@drawable/lightopen" android:state_pressed="true"/>
    <item android:drawable="@drawable/lightoff" android:state_pressed="false"/>
    <item android:drawable="@drawable/lightoff"></item>

</selector>


第三步:在main.xml文件中完成Button控件代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/lightoff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/lightctrl" 
        android:gravity="center" />

</LinearLayout>

注意android:background="@drawable/selector" ,selector为第二步中xml文件的名字,而不是图片的名字。