开发者

How to set up an onTouchListener that changes an ImageView image resource?

I want to setup up an onTouchListener that changes an ImageViews image resource on ACTION_UP and ACTION_DOWN. Here is my code:

    // 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(even开发者_开发知识库t.getAction() == MotionEvent.ACTION_UP) {
                // Button was released, reset button background
                v.setImageResource(R.drawable.button_white);
                return true;
            }

            return false;
        }

    };

This code does not compile because View does not have the method setImageResource, only ImageView. But how do I tell the listener that an ImageView is being used?


Cast the incoming View to an ImageView.

Sample code:

@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;
}


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;
    }

};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜