How can I give an imageview click effect like a button on Android?

前端 未结 30 2268
情歌与酒
情歌与酒 2020-11-28 01:50

I have imageview in my Android app that I am using like a button with the onClick event given, but as you might guess it is not giving imageview a clickable effect when clic

30条回答
  •  情歌与酒
    2020-11-28 02:00

    You can design different images for clicked/not clicked states and set them in the onTouchListener as follows

    final ImageView v = (ImageView) findViewById(R.id.button0);
            v.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    switch (arg1.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        v.setImageBitmap(res.getDrawable(R.drawable.img_down));
                        break;
                    }
                    case MotionEvent.ACTION_CANCEL:{
                        v.setImageBitmap(res.getDrawable(R.drawable.img_up));
                        break;
                    }
                    }
                    return true;
                }
            });
    

    The better choice is that you define a selector as follows

    
        
        
    
    

    and select the image in the event:

    v.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
                    return true;
                }
            });
    

提交回复
热议问题