根据文本值更改文本颜色

时间:2013-05-08 00:14:41

标签: android textview

我试图弄清楚如何根据文本的值更改TextView的颜色。 TextView已经从另一个活动发送,我有一部分正常工作。我想要的是一种根据TextView中的内容更改文本颜色的方法。因此,如果之前的Activity发送类似“11 Mbps”的值作为TextView,那么我希望该文本颜色为黄色,“38 Mbps”为绿色,1 Mbps为红色。如果这有用的话,我正在使用eclipse。

这就是我将TextView发送到另一个活动的方式。 “showmsg”只是发送到另一个页面的用户名。

buttonBack.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v){
            final TextView username =(TextView)findViewById(R.id.showmsg);
            String uname = username.getText().toString();

            final TextView wifistrength =(TextView)findViewById(R.id.Speed);
            String data = wifistrength.getText().toString();



                startActivity(new Intent(CheckWiFiActivity.this,DashboardActivity.class).putExtra("wifi",(CharSequence)data).putExtra("usr",(CharSequence)uname));


        }
    });

这就是我在其他活动中收到它的方式

Intent i = getIntent();
               if (i.getCharSequenceExtra("wifi") != null) {
                final TextView setmsg2 = (TextView)findViewById(R.id.Speed);
                setmsg2.setText(in.getCharSequenceExtra("wifi"));               
               }

这一切都很好但我不知道如何根据文本的值更改TextView的颜色。任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:4)

您显然希望根据您从上一个活动收到的String中的数字来设置颜色。因此,您需要从String中解析出来,将其保存到int,然后根据数字设置,设置TextView的颜色。

String s = in.getCharSequenceExtra("wifi");
// the next line parses the number out of the string
int speed = Integer.parseInt(s.replaceAll("[\\D]", ""));
setmsg2.setText(s);
// set the thresholds to your liking
if (speed <= 1) {
    setmsg2.setTextColor(Color.RED);
} else if (speed <= 11) {
    setmsg2.setTextColor(Color.YELLOW);
else {
    setmsg2.setTextColor(Color.GREEN);
}

请注意,这是一个未经测试的代码,可能包含一些错误。

解析它的方法来自here

答案 1 :(得分:1)

首先,从String中获取所有非数字字符,然后将其转换为integer。然后在新值上使用switch并相应地设置颜色

String color = "blue";   // this could be null or any other value but I don't like initializing to null if I don't have to
int speed = i.getCharSequenceExtra("wifi").replaceAll("[^0-9]", "");    // remove all non-digits here
switch (speed)
{
    case (11):
        color = "yellow";
        break;
    case (38):
        color = "green";
        break;
    case(1):
        color = "red";
        break;
}
setmsg2.setTextColor(Color.parseColor(color);

Here is a little site with some handy information

Color Docs