简体   繁体   中英

Android: How to Set Color of Text Using a String

I have an intent that brings two strings. 1 is the string for the message and the other is a string for the color.

The code below shows that the 2 strings are received. The "message" string is displayed in the textview which works correctly. However I need the string "messagecolor" to set the color of the textview.

I have a colors.xml file where the colors blue, green and red are defined.

So if the string "messagecolor" is blue to text will be blue. The same for red and green. If the string "messagecolor is not blue,red or green then the text will just appear black.

If someone could help me solve this it would be most appreciated.

Thank you

// Get the message from the intent
    Bundle bundle = getIntent().getExtras();
    String messagecolor = bundle.getString(MainActivity.EXTRA_MESSAGE_COLOR);
    String message = bundle.getString(MainActivity.EXTRA_MESSAGE);


    // Create the text view
    TextView textView = new TextView(this);
    textView.setTextColor(getResources().getColor(R.color.blue));
    textView.setTextSize(100);
    textView.setText(message);

与其尝试匹配由哪个字符串表示的颜色,不为什么不传递资源ID本身?

Try

if (message.equals("messageBlue")) {
    textView.setTextColor(getResources().getColor(R.color.blue));
} else if (message.equals("messageGreen")) {
    textView.setTextColor(getResources().getColor(R.color.green));
} else if (message.equals("messageRed")) {
    textView.setTextColor(getResources().getColor(R.color.red));
} else //default
    textView.setTextColor(getResources().getColor(R.color.black));
text.setText(Html.fromHtml("<font color='red'>R</font>"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM