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
Simply just use an ImageButton.
I did as follows in XML - with 0 padding around the image and ripple ontop of the image:
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/my_image"
android:clickable="true"
android:focusable="true"
android:src="?android:attr/selectableItemBackground" />
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.
Set the selectable background to the ImageView and add some padding. Then attach the OnClickListener
.
<ImageView
android:id="@+id/your_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image"
android:padding="10dp"
android:background="?android:attr/selectableItemBackground"/>
It's possible to do with just one image file using the ColorFilter method. However, ColorFilter expects to work with ImageViews and not Buttons, so you have to transform your buttons into ImageViews. This isn't a problem if you're using images as your buttons anyway, but it's more annoying if you had text... Anyway, assuming you find a way around the problem with text, here's the code to use:
ImageView button = (ImageView) findViewById(R.id.button);
button.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
That applies a red overlay to the button (the color code is the hex code for fully opaque red - first two digits are transparency, then it's RR GG BB.).
If you want ripple when tapped, it can be given by this code :
<ImageView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</ImageView>
Similarly, you can implement click effect for TextView
<TextView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</TextView>