Search code examples
androidandroid-fragmentactivityandroid-button

Android set color filter in fragment activity


So I am trying to set the colorFilter of an ImageView that is inside of a fragment activity. I can click on the button and it works as expected except when I try to set the colorFilter it crashes and says:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.drawable.Drawable.setColorFilter(int, android.graphics.PorterDuff$Mode)' on a null object reference

How can this be null if I am already clicking on it and it is working? How do I fix it? Here is my onCreateView:

myButton = (ImageView) view.findViewById(R.id.mybutton);
myButton.setOnClickListener(this);

// testing
myButton.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);

** ANSWER ** My solution as pointed out, I was using app:srcCompat="@drawable to set my imageView and not a background. So I just removed the .getBackground. Here is my solution:

myButton.setColorFilter(ContextCompat.getColor(context, R.color.Gray), android.graphics.PorterDuff.Mode.MULTIPLY);

Solution

  • This is because your getBackground is giving null. You have a imageview. May be you set its "src" not "background" in xml. If you want to continue with same, then set background in xml.

    Thanks