如何使TextView形状变为圆形并根据条件设置不同的背景颜色 [英] How to make TextView shape circle and set different background color based on condition

查看:130
本文介绍了如何使TextView形状变为圆形并根据条件设置不同的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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"));
}

推荐答案

如果您的颜色比较少,则可以为每种颜色创建一个可绘制的文件,例如,创建文件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.

要通过代码更改颜色,请执行以下操作:

To change the color from code:

TextView v = (TextView) findViewById(R.id.my_text_view);
v.setBackgroundResource(R.drawable.bg_blue);

这篇关于如何使TextView形状变为圆形并根据条件设置不同的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆