2013-05-08 48 views
2

我想弄清楚如何根据文本的值改变TextView的颜色。 TextView已从其他活动发送我有那部分工作正常。我想要的是一种基于TextView中的内容来改变文本颜色的方法。因此,如果以前的活动发送像“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的基础的价值的颜色文本。任何帮助将非常感激。

回答

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

+0

+1,我没有测试过,要么,但它看起来像它会工作。我开始发帖,几乎没有看到你的时候,但我喜欢在可能的时候使用'switch',只用一行来调用函数(这里是'setText()'。)好的答案 – codeMagic 2013-05-08 00:49:41

+0

这正是我在找的东西。我只是复制和粘贴,但我会破坏此代码的每一部分,以了解更多关于编程,并最终扩展它。我只做了几个月,但感谢像你这样有帮助的程序员,我做了很多 – SmulianJulian 2013-05-08 01:04:24

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

+0

这个答案也非常有帮助,但我不能投票,因为我没有足够的代表。谢谢你的链接。 – SmulianJulian 2013-05-08 01:05:06

+0

@SmulianJulian没问题,很高兴我能帮到你。 – codeMagic 2013-05-08 01:55:56

+0

那么,这里'switch'语句的问题是,它只能在速度正好是1,11或者38时才能处理。如果是其他的东西,那么文本将保持蓝色,但也许值不能是其他值在他的c谁知道。只是说它不会和我的代码做同样的事情。 – zbr 2013-05-08 11:42:15