Hamid Reza
Hamid Reza

Reputation: 664

Draw shape - Convert XML into Code

I need to convert my shape into java code ( generate programmatic) to set color of my shape in a dynamic way, here is my shape XML

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:width="5dp"
    android:height="50dp"
    android:bottom="0dp"
    android:left="0dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/white" />
    </shape>
</item>

<item
    android:width="50dp"
    android:height="5dp"
    android:bottom="0dp"
    android:top="45dp">
    <shape android:shape="rectangle">
        <solid android:color="@color/white" />
    </shape>
</item>

I use this in my activity and generate a beautiful shape like the pic blow

this is my screen shot

and this goes my activity XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gray"
android:gravity="center"
android:orientation="vertical"
tools:context="ir.vasl.testdrawable.MainActivity">

<RelativeLayout
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:background="@color/black">

    <RelativeLayout
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@drawable/border_list_item_album_art" />

    <RelativeLayout
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/border_list_item_album_art"
        android:rotation="180" />

</RelativeLayout>

Now I just need to generate this shape by code to set border colors in a dynamic way, thanks for your help ;)

UPDATE:

I achieve my shape color changing with this code, hope it helps you guys

    LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(MainActivity.this
            , R.drawable.border_list_item_album_art);
    shape.setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
    findViewById(R.id.border_left).setBackgroundDrawable(shape);

Upvotes: 0

Views: 459

Answers (1)

saDashiv sinha
saDashiv sinha

Reputation: 165

Here is what you can do.

First get your drawable in the Java code

LayerDrawable shape = (LayerDrawable) 
getResources().getDrawable(R.drawable.your_shape)

Then change the color like this

shape.setColor(Color.RED);

Also, getDrawable is depricated, so you might also use this

LayerDrawable shape = (LayerDrawable) 
ContextCompat.getDrawable(MainActivity.this,R.drawable.shape_name)

Hope it helped

Upvotes: 2

Related Questions