Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 clicked. How can I achieve that?

like image 851
Burak Dede Avatar asked Jan 06 '11 17:01

Burak Dede


People also ask

How do you make an ImageView clickable like a simple button?

Using clickable images You can turn any View , such as an ImageView , into a button by adding the android:onClick attribute in the XML layout. The image for the ImageView must already be stored in the drawable folder of your project.

Can ImageView be used as button?

ImageView is used when we want to work with images or we want to display them in our application. So, this article will give you a complete idea of using an ImageView as a Button in android studio. So, without wasting further time let's go to the article and read how we can achieve this task.

Can ImageView be clickable?

For example, you can make an ImageView act like a simple Button by adding android:onClick to the ImageView . In this task you make the images in your layout clickable.


1 Answers

You can do this with a single image using something like this:

     //get the image view     ImageView imageView = (ImageView)findViewById(R.id.ImageView);      //set the ontouch listener     imageView.setOnTouchListener(new OnTouchListener() {          @Override         public boolean onTouch(View v, MotionEvent event) {              switch (event.getAction()) {                 case MotionEvent.ACTION_DOWN: {                     ImageView view = (ImageView) v;                     //overlay is black with transparency of 0x77 (119)                     view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);                     view.invalidate();                     break;                 }                 case MotionEvent.ACTION_UP:                 case MotionEvent.ACTION_CANCEL: {                     ImageView view = (ImageView) v;                     //clear the overlay                     view.getDrawable().clearColorFilter();                     view.invalidate();                     break;                 }             }              return false;         }     }); 

I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.

like image 92
Mr Zorn Avatar answered Sep 24 '22 17:09

Mr Zorn