I have a code that changes the tint of an image button when clicked.
Here’s the java code
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent me)
{
if (me.getAction() == MotionEvent.ACTION_DOWN)
{
button.setColorFilter(Color.argb(150, 155, 155, 155));
}
else if (me.getAction() == MotionEvent.ACTION_UP)
{
button.setColorFilter(Color.argb(0, 155, 155, 155));
}
return false;
}
});
The code is working fine on this xml, the button dims when clicked.
<ImageButton
android:id="@+id/schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="138dp"
android:layout_y="169dp"
android:src="@drawable/schedule"
/>
But it is not working on this xml, the button doesn’t dim when clicked.
<ImageButton
android:id="@+id/schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="138dp"
android:layout_y="169dp"
android:background="@drawable/schedule"
/>
Why does if I use android:background the setColorFilter doesn’t work? but if I use android:src it is working fine.
The simple answer is that:
android:backgroundattribute refers to a method of the View class,android:srcrefers to a methods of ImageView,and each class maintains their own background resources. So when you call the ImageView method
setColorFilter(), it applies the filter to its local background resource (the one set bysrc) andsetColorFilter()has no knowledge of the View resource set bybackground.