Using default ShapeDrawable in StateListDrawable in Android 4.2

Anyone having problems using the new ShapeDrawable() in StateListDrawable in android 4.2? I used this:

 ShapeDrawable bg = new ShapeDrawable(); //default Ctor ShapeDrawable hl = new ShapeDrawable(); hl.getPaint().setColor(color1); bg.getPaint().setColor(color2); StateListDrawable s1 = new StateListDrawable(); s1.addState(new int[]{android.R.attr.state_pressed}, hl); s1.addState(new int[]{}, bg); 

But this no longer works in Android 4.2 , throwing a nullpointerexception :

 java.lang.NullPointerException at android.graphics.drawable.ShapeDrawable.mutate(ShapeDrawable.java:387) at android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:315) at android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:106) at android.graphics.drawable.StateListDrawable.addState(StateListDrawable.java:89) 

I fixed the problem by changing the constructor of my ShapeDrawable :

 ShapeDrawable bg = new ShapeDrawable(new RectShape()); ShapeDrawable hl = new ShapeDrawable(new RectShape()); 

Now this works fine , but I would like to know why this does not work with the standard constructor =)

Thank you for your time:)

+8
android drawable android-drawable android-4.2-jelly-bean
source share
1 answer

the implementation of DrawableContainer.selectDrawable() has changed in Android 4.2, and ShapeDrawable should use a construct with args.

If you use the default constructor, then when you call mutate() mShape is null , so mShape.clone () will throw a CloneNotSupportedException and return null . so you get a NullPointerException .

+7
source share

All Articles