Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change text color based on value of text

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.

like image 481
SmulianJulian Avatar asked Dec 03 '25 18:12

SmulianJulian


1 Answers

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.

like image 101
zbr Avatar answered Dec 06 '25 08:12

zbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!