按下和释放时如何更改ImageButton的图像?

时间:2011-06-30 06:17:38

标签: android imagebutton

我希望在我的Android应用程序中,ImageButton在按下并释放时更改其图像,当再次按下它时,ImageButton的图像将被更改回来,如何那样做?

3 个答案:

答案 0 :(得分:8)

创建一个放在drawable文件夹中的选择器(它是一个xml文件)。并且在xml实际图像android:background="@drawable/imageselector"的xml实例的五个路径中,或者在程序中也可以使用imageview.setBackgroundDrawable(R.drawable.imageselector)获得相同的

以下是我的选择器 的 imageselector.xml

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

答案 1 :(得分:7)

答案 2 :(得分:0)

您可以使用图像视图:

<ImageView
            android:id="@+id/iv1"
            android:src="@drawable/ic_new_delete0"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:visibility="visible" />

代码背后:

ImageView _iv1 = _activity.FindViewById<ImageView>(Resource.Id.iv1);

        _iv1.Touch += (object sender, View.TouchEventArgs e) => {
            if (e.Event.Action == MotionEventActions.Down)
            {
                _iv1.SetImageResource(Resource.Drawable.ic_new_delete);
                //Do the task when button is pressed
            }
            else if (e.Event.Action == MotionEventActions.Up)
            {
               _iv1.SetImageResource(Resource.Drawable.ic_new_delete0);
               //do the task when button is released
            }
        };