0

I am working on creating a traffic light application. its very simple just a TextView and button. I wanted the TextView to be circular so I created a recourse file in drawable called circular and set it as the label background.

<TextView
        android:id="@+id/traffic_light_label"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/circular"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

The label does change from a square a circle shape in the xml file. but when I try changing the background color in the main activity the shape reverts back to square I tried calling the drawable object in the main activity as well but it did not work. any suggestion on what I should do.

Main activity file: this is what causes the shape to revert back to square

        light=findViewById(R.id.traffic_light_label);
        light.setBackgroundColor(getResources().getColor(R.color.red));

circular recourse file

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <size android:width="100dp"
          android:height="100dp"/>

    <solid android:color="#FF0000"/>
</shape>
Aimex
  • 51
  • 6

2 Answers2

2

Update your drawable file to be like this:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="oval">
        <solid android:color="@color/transparent" />
        <stroke android:width="1dp" android:color="@color/black" />
    </shape>
</item>
<item>
    <shape android:shape="oval">
        <solid android:color="#FF0000" />
    </shape>
</item>
</layer-list>

After doing that and adding it to your TextView as background, you can edit your java file also and add this:

TextView light = findViewById(R.id.traffic_light_label);
light.getBackground().setColorFilter(getResources().getColor(R.color.red), PorterDuff.Mode.SRC_IN);
Adinia
  • 3,722
  • 5
  • 40
  • 58
Ali Hamed
  • 316
  • 1
  • 1
  • 12
1

You Don't need to gives background color to that view because you already gave a background in the xml file.

If you need to change only color of a background then you just need to add background Tint property on that view.

Refer this Answer for more specific details on background and background tint just for your knowledge.

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

   textView.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#57B92F"))

Use this code on your view it works fine in my case.