levente
levente

Reputation: 95

Change colour of a shape in Java for Android after user input

I have a simple shape that is stored in rect.xml, and included in an other xml as a 'background' attribute of a 'View'. The two codes are:

\res\layout\rect.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape"
android:shape="rectangle" >
<stroke android:width="2dp" android:color="#aaaaff" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"    >
</padding>
<solid android:color="#E6121A" />
<gradient
android:startColor="#000000"
android:endColor="#aaaaff"
android:angle="90"  >
</gradient>

<corners
android:radius="10dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" >
</corners>

</shape> 

my other view, that is displayed as content of an activity includes this:

<View
    android:id="@+id/myRectangleView"
    android:layout_width="25dp"
    android:layout_height="125dp"
    android:layout_below="@+id/tableLayout1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="35dp"
    android:background="@layout/rect" />

I would like to set the android:endColor attribute to another colour, the startColor is always the same. Thanks for the answers in advance!

Upvotes: 0

Views: 691

Answers (1)

Jorah Mormont
Jorah Mormont

Reputation: 126

I haven't tested this, but based on the information here you should be able to set the colors with this:

GradientDrawable gradient = (GradientDrawable)yourView.getBackground();

int startColor = Color.BLACK;
int endColor = Color.RGB(0, 2, 255);
gradient.setColors(new int[]{ startColor, endColor });

Please note that GradientDrawable.setColors() was added in API level 16/Android 4.1 (thanks unrulygnu!), and to support earlier versions you need to create and set a new GradientDrawable every time you want to change colors, like this:

GradientDrawable gradient = new GradientDrawable(Orientation.TOP_BOTTOM, new int[]{startColor, endColor});
gradient.setShape(GradientDrawable.RECTANGLE);
yourView.setBackgroundDrawable(gradient);

Upvotes: 3

Related Questions