gpt4 book ai didi

java - 如何设置一个改变ImageView图像资源的onTouchListener?

转载 作者:行者123 更新时间:2023-12-01 17:35:43 24 4
gpt4 key购买 nike

我想设置一个 onTouchListener 来更改 ACTION_UP 和 ACTION_DOWN 上的 ImageViews 图像资源。这是我的代码:

    // Setup a basic upDownListener that registers UP and DOWN actions and changes the
// view image resource accordingly
View.OnTouchListener upDownListener = new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
// Button was pressed, change button background
v.setImageResource(R.drawable.button_white_pressure);
return true;
} else if(event.getAction() == MotionEvent.ACTION_UP) {
// Button was released, reset button background
v.setImageResource(R.drawable.button_white);
return true;
}

return false;
}

};

这段代码无法编译,因为View没有setImageResource方法,只有ImageView。但我如何告诉听众正在使用 ImageView?

最佳答案

将传入的 View 转换为 ImageView

示例代码:

@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView) v;

if (event.getAction() == MotionEvent.ACTION_DOWN) {
iv.setImageResource(R.drawable.button_white_pressure);
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
iv.setImageResource(R.drawable.button_white);
return true;
}

return false;
}

关于java - 如何设置一个改变ImageView图像资源的onTouchListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6586740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com