How to make TextView shape circle and set different background color based on condition
If you have a relatively small amout of colors, you can create a drawable file for each color, for example create a file bg_red.xml:
<?xml version="1.0" encoding="utf-8"?>
<item xmlns:android="http://schemas.android.com/apk/res/android">
<shape>
<solid android:color="#f00" />
<corners
android:topLeftRadius="30dp"
android:topRightRadius="30dp"
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
/>
</shape>
</item>
Then assign define the TextView:
<TextView
android:id="@+id/tv"
android:layout_height="60dp"
android:layout_width="60dp"
android:text="X"
android:textColor="#fff"
android:textSize="20sp"
android:background="@drawable/bg_red"
android:gravity="center_vertical|center_horizontal"
/>
Note that the width is twice the radius of the background corner radius.
To change the color from code:
TextView v = (TextView) findViewById(R.id.my_text_view);
v.setBackgroundResource(R.drawable.bg_blue);
To add up to the accepted answer, adding size tag inside shape and making sure height and width is large enough will make sure the background is circle even if textView has many characters!
<shape> <solid android:color="#f00" /> <corners android:topLeftRadius="30dp" android:topRightRadius="30dp" android:bottomLeftRadius="30dp" android:bottomRightRadius="30dp" /> <size android:height="25dp" android:width="25dp"/> </shape>
TextView textView = (TextView) findViewById(R.id.my_text_view);
Drawable drawable = textView.getBackground();
drawable.setColorFilter(getResources().getColor(color), PorterDuff.Mode.SRC_IN);
works for me