Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

android - How to make TextView shape circle and set different background color based on condition

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.

Code I have used:

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"));
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...