I'm trying to change the border colour of my TextView
programmatically, depending on the if
condition in my activity. Here's my ViewContact.java
code:
if (bob == 0) {
//change colour depending on value
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat
.getDrawable(ViewContact.this,R.drawable.textboxes);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.textbox_shape);
gradientDrawable.setColor(Color.parseColor("#DA850B")); // change color
}
if (bob == 1) {
LayerDrawable layerDrawable = (LayerDrawable) ContextCompat
.getDrawable(ViewContact.this,R.drawable.textboxes);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
.findDrawableByLayerId(R.id.textbox_shape);
gradientDrawable.setColor(Color.parseColor("#0A7FDA")); // change color
}
if (bob == 2) {
etc...
}
I've looked here Changing color in a shape inside a layer-list programmatically and here Android change color stroke (border) programmatically and elsewhere for a solution but can't get it working.
Here is the xml
for my TextView
in the ViewContact.java
activity, activity_view_contact.xml
:
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:background="@drawable/textboxes"
/>
And here is textboxes.xml
:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--space between each text box-->
<item
android:top="3dp"
android:id="@+id/textbox_shape"
>
<shape android:shape="rectangle">
<!--formatting of colour inside the box-->
<solid android:color="@android:color/transparent" />
<!--formatting of lines on the box-->
<stroke
android:width="1dip"
/>
<corners android:radius="3dp"/>
<!--text formatting in the box-->
<padding
android:textSize="30dp"
android:top="15dp"
android:bottom="1dp"
android:left="20dp"
android:right="20dp"/>
</shape>
</item>
</layer-list>