如何使TextView形状为圆形并根据条件设置不同的背景颜色 [英] How to make TextView shape circle and set different background color based on condition
问题描述
我有一个TextView
,我想要的是把TextView
的形状做成圆形,然后根据我使用的不同条件设置不同的背景颜色.我可以根据不同的条件设置背景颜色,但不能使 TextView
形状为圆形.那么如何做到这一点.请帮我解决这个问题.
I have a TextView
, what I want is to make the TextView
shape circle and then set different background colors based on different conditions I have used. I am able to set Background color based on different conditions but not able to make the TextView
shape circle. So how that can be done. Please help me to solve this out.
我使用过的代码:
TextView txt_stage_display = (TextView)findViewById(R.id.txt_stage_display);
if(m_enStage[position] == enSTAGE_START)
{
txt_stage_display.setBackgroundColor(Color.parseColor("#D48393"));
}
else if(m_enStage[position] == enSTAGE_FLOW)
{
txt_stage_display.setBackgroundColor(Color.parseColor("#D48393"));
}
else if(m_enStage[position] == enSTAGE_SAFE)
{
txt_stage_display.setBackgroundColor(Color.parseColor("#66B0CC"));
}
else if(m_enStage[position] == enSTAGE_UNSAFE)
{
txt_stage_display.setBackgroundColor(Color.parseColor("#D8C627"));
}
else if(m_enStage[position] == enSTAGE_FERTILE)
{
txt_stage_display.setBackgroundColor(Color.parseColor("#67A05E"));
}
else
{
txt_stage_display.setBackgroundColor(Color.parseColor("#808080"));
}
推荐答案
如果你的颜色数量比较少,你可以为每种颜色创建一个drawable文件,例如创建一个文件bg_red.xml:
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>
然后分配定义TextView:
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.
从代码更改颜色:
TextView v = (TextView) findViewById(R.id.my_text_view);
v.setBackgroundResource(R.drawable.bg_blue);
这篇关于如何使TextView形状为圆形并根据条件设置不同的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!