android shape xml rotated drawable change color programmatically

android, layer-list, layerdrawable, xml

Solution

This is somewhat tricky and involves a lot of casts:

TextView view = (TextView) findViewById( R.id.my_text_view );

// Get the drawable from the view, if you're using an imageview src
// element you'll go with view.getDrawable()
LayerDrawable layers = (LayerDrawable) view.getBackground();

// Now get your shape by selecting the id
RotateDrawable rotate = (RotateDrawable) layers.findDrawableByLayerId( R.id.shape_id );

// Finally you can access the underlying shape
GradientDrawable drawable = (GradientDrawable) rotate.getDrawable();

// ... and do you fancy things
drawable.setColor( ... );

Problem

This is a xml for triangle shape: ``` <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/shape_id"> <rotate android:fromDegrees="45" android:toDegrees="45" android:pivotX="-40%" android:pivotY="87%" > <shape android:shape="rectangle" > <stroke android:width="10dp"/> </shape> </rotate> </item> </layer-list> ``` And this is a background of a textview ``` <TextView android:id="@+id/headlineSelect_TXT2" android:layout_width="50dp" android:layout_height="50dp" android:layout_weight="1" android:background="@drawable/category_triangle_shape1" android:visibility="invisible" /> ``` And I want to change color of shape programmatically. I tried this but I am getting null pointer exception ``` LayerDrawable bgDrawable = (LayerDrawable) getActivity() .getResources() .getDrawable(R.drawable.category_triangle_shape1); final GradientDrawable shape = (GradientDrawable) bgDrawable .findDrawableByLayerId(R.id.shape_id); shape.setStroke(10,Color.GREEN); ``` How can I do that? Thanks for help.

Original source