将突出显示的状态图像指定给Android Image Button

时间:2015-10-03 17:24:28

标签: android button

我按照其他地方的步骤操作,我制作了一个像这样的xml文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/yeah2"
        android:state_pressed="true" />
    <item android:drawable="@drawable/yeah" />

我的按钮的活动xml如下所示:

<ImageButton

    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:id="@+id/imageButton"
    android:onClick="play1"
    android:layout_below="@+id/textView"
    android:layout_alignParentStart="true"
    android:layout_marginTop="100dp"
    android:src="@drawable/yeah"
    android:clickable="false"
    android:nestedScrollingEnabled="true"
    android:background="@drawable/highlight" />

如何将突出显示的状态图像指定给Android图像按钮?

1 个答案:

答案 0 :(得分:0)

使xml像这样

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Remember: order is important. First matching state(s) is rendered) -->
<item 
    android:state_selected="true" 
    android:drawable="@drawable/yeah" />
<item 
    android:drawable="@drawable/yeah2" />

然后在Java中执行以下操作

imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable.ImageButton));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

public void onClick(View button) {
    //Set the button's appearance
    button.setSelected(!button.isSelected());

    if (button.isSelected()) {
        //Handle selected state change
    } else {
        //Handle de-select state change
    }

}

});