Reputation: 802
I am trying to figure out how to change the color of TextView based on the value of the text. TextView has been sent from another activity I have that part working fine. What I want is a way to change the color of the text based on what is in the TextView. So if previous Activity sends a value like "11 Mbps" as TextView then I would like that text color to be yellow, "38 Mbps" green, and 1 Mbps red. I'm using eclipse if that helps at all.
This is how I'm sending the TextView to another activity. "showmsg" is just username sent to another page.
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));
}
});
And this is how I receive it in the other activity
Intent i = getIntent();
if (i.getCharSequenceExtra("wifi") != null) {
final TextView setmsg2 = (TextView)findViewById(R.id.Speed);
setmsg2.setText(in.getCharSequenceExtra("wifi"));
}
This all works fine but I don't have a clue how to change the color of TextView based of the value of the text. Any help would be really appreciated.
Upvotes: 3
Views: 3176
Reputation: 44571
First, get all of the non-numeric characters out of your String
and convert it to an integer
. Then use a switch
on the new value and set the color accordingly
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
Upvotes: 1
Reputation: 7037
You obviously want to set the color according to the number in the String
you received from the previous Activity. So you need to parse it out of the String
, save it to an int
and then according to what the number is, set the color of your 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);
}
Please notice that this is an untested code, it might contain some mistakes.
The way to parse it comes from here.
Upvotes: 4