Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom background xml send attribute

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.

like image 740
Meir Avatar asked Oct 21 '22 08:10

Meir


1 Answers

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 !!

like image 190
Mehul Joisar Avatar answered Oct 29 '22 19:10

Mehul Joisar