I crated a small app, which cycles through tinted images of an ImageView on clicks.
It works well with the image set in the layout file, but it does not work when setting the image from the code like below.
Any help appreciated.
public class MainActivity extends Activity {
private ImageView mPic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPic = (ImageView) findViewById(R.id.pic);
mPic.setBackgroundResource(R.drawable.msh);
mPic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random=new Random();
ColorFilter cf = new PorterDuffColorFilter(Color.argb(192, random.nextInt(255), random.nextInt(255), random.nextInt(255)),Mode.SRC_ATOP);
mPic.setColorFilter(cf);
}
});
}
}
The color filter is applied to the ImageView
content, not its background. Use ImageView#setImageResource(int resId) to set the content and color filter will be applied.
If you need to add the ColoFilter
to ImageView
's background, you can try something like mPic.getBackground().setColorFilter()
(assuming that getBackground()
returns non-null value).