2013-05-08 49 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