如何设置更改ImageView图像资源的onTouchListener?

时间:2011-07-05 17:48:06

标签: java android

我想设置一个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?

2 个答案:

答案 0 :(得分:3)

将传入的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;
}

答案 1 :(得分:2)

View.OnTouchListener upDownListener = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView v = (ImageView) v;
        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;
    }

};