5

I have the following xml file:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /> 
</shape>

as you can see, all it is, is a shape with rounded corners. I use it for background in activity layouts as follows:

android:background="@drawable/rounded_corners"

The shape in the file is currently set to white. In different layouts I need different colors. Do I need to create a different shape xml file for each color? I need a way to just specify in the layout what color to send to the background, and that way I can use the same xml for any color I want.

Thanks.

Meir
  • 1,943
  • 5
  • 22
  • 38
  • This might be what you are looking for: http://stackoverflow.com/questions/11376516/change-drawable-color-programmatically – TronicZomB May 31 '13 at 12:27
  • I am looking for a way to set it via the xml. Something like background="red" src="drawable.." – Meir May 31 '13 at 12:30
  • In that case, I do not believe this to be possible and you will need multiple shapes. Though I could be wrong, in which case I would like to know how to do this too :) – TronicZomB May 31 '13 at 12:33
  • My question can also be translated to "Is there a way to *bind* custom attributes to xml?" May something like wpf allows – Meir May 31 '13 at 12:38
  • Is it possible that I can use attrs.xml for that? Or is that only for custom components? – Meir Jun 02 '13 at 06:41

1 Answers1

3
Do I need to create a different shape xml file for each color?
  • Yes,If you want to apply different color for different layout files from the layout's xml file itself
  • No,If you apply different color for different layout files from its java (Activity) file.

Solution for option 2:

//shape drawable (rounded_corners.xml)

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /> 
</shape>

//layout file

        <Button 
            android:id="@+id/mButton"
            ...
            android:background="@drawable/rounded_corners"
            />

//java (Activity) file

Button mButton = (Button) findViewById(R.id.mButton); 
ShapeDrawable rounded_corners = (ShapeDrawable )mButton.getBackground();
rounded_corners.getPaint().setColor(Color.RED);

I hope it will be helpful !!

Mehul Joisar
  • 15,348
  • 6
  • 48
  • 57