4

I have this drawable shape.xml that looks like this nothing special:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">

    <corners android:radius="4dp"/>
    <solid android:color="?colorPrimary"/>
</shape>

When I run on below api 21 it crashed since I think it´s not supported to use
the "?colorPrimary".

The user can select different themes right so what can I use instead of the "?colorPrimary" on below api 21?

If I set it like this:

<solid android:color="@color/colorPrimary" />

then I will set same color for all my themes and that´s not desirable.

In my styles.xml I have like 10 different themes user can select.

I understand I must move the drawable shape.xml into the drawable-v21 folder but how should I change the same shape.xml above in the default drawable folder to give me same functionality?

Tord Larsen
  • 2,670
  • 8
  • 33
  • 76
  • Why don't you try this -- android:textColor="@color/colorPrimary" – AbhayBohra Jun 27 '17 at 11:22
  • This shape.xml is used as a background for a ListView Item. In my blue theme the background is blue and in my red theme the B is read – Tord Larsen Jun 27 '17 at 12:31
  • I ended up doing like [this](https://stackoverflow.com/questions/8041537/how-to-reference-style-attributes-from-a-drawable) from the accepted answer [here](https://stackoverflow.com/questions/8041537/how-to-reference-style-attributes-from-a-drawable) – Tord Larsen Jun 28 '17 at 08:59

3 Answers3

4

We have another option Instead of creating shape.xml in drawable at compile time create it by using java at runtime

get color of theme at runtime and use it while creating shape at runtime

GradientDrawable gradientDrawable=new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.OVAL);
gradientDrawable.setColor(getResources().getColor(R.color.colorAccent));
gradientDrawable.setSize(200,200);
gradientDrawable.setCornerRadius(100);

Or you can inflate the existing shape from xml and change it's properties like this,

GradientDrawable shapeDrawable= (GradientDrawable) 
ContextCompat.getDrawable(this,R.drawable.shape);
shapeDrawable.setColor(getResources().getColor(R.color.colorPrimary));
imageView.setImageDrawable(shapeDrawable);
Kamlakar Kate
  • 397
  • 1
  • 6
  • 11
0

i think you should try make different values folder in your res folder like

values-v19 values-v21 etc.

and also you have check one thing in your java class to preventing force close

// Check if we're running on Android 5.0 or higher

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Call some material design APIs here
} else {
    // Implement this feature without material design
}
  • How can different values folders set my shape.xml color. Feels like I have to create 10 shape.xml files one for each theme dunno – Tord Larsen Jun 27 '17 at 12:43
0

You have to write different drawable for different color theme

Kamlakar Kate
  • 397
  • 1
  • 6
  • 11