ImageView:在按下和发布时更改图像

gio*_*ozh 1 android android-imageview

我会在按下时更改imageView图片,并在压力释放时再次更改.ImageView包含一个按钮的图片,当按下时,我会通过更改图像向用户提供反馈(例如,当他按下正常按钮时).这是我的代码:

final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i("IMAGE", "motion event: " + event.toString());
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            imageView.setImageResource(R.drawable.button_hover);
        }
        case MotionEvent.ACTION_UP: {
            imageView.setImageResource(R.drawable.button);
        }
        }
        return false;
    }
    });
Run Code Online (Sandbox Code Playgroud)

这是xml

 <ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="std_button"
    android:src="@drawable/button" />
Run Code Online (Sandbox Code Playgroud)

但它不起作用.如果我只使用ACTION_DOWN事件,图像改变我想要,有什么问题?

Ada*_*ski 6

在 drawable 文件夹中制作选择器 xml,内容如下:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_green" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_red"/>
    </selector>
Run Code Online (Sandbox Code Playgroud)

  • 将此可绘制的 xml 文件设为 android:src="@drawable/selector" (2认同)

Che*_*rot 5

尝试添加休息; 在每个案件之后,

并且正如giozh所说,在onTouch内部我总是返回false,因此触摸事件结果总是不会被消耗掉.只需在每个case语句后返回true即可.