【问题标题】:Android: How to Set Color of Text Using a StringAndroid:如何使用字符串设置文本颜色
【发布时间】:2014-03-14 17:35:10
【问题描述】:

我的意图是带来两个字符串。 1 是消息的字符串,另一个是颜色的字符串。

下面的代码显示收到了 2 个字符串。 “消息”字符串显示在正常工作的文本视图中。但是我需要字符串“messagecolor”来设置文本视图的颜色。

我有一个 colors.xml 文件,其中定义了蓝色、绿色和红色。

因此,如果字符串“messagecolor”为蓝色,则文本将为蓝色。红色和绿色也一样。如果字符串 "messagecolor 不是蓝色、红色或绿色,则文本将显示为黑色。

如果有人能帮我解决这个问题,将不胜感激。

谢谢

// 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);

【问题讨论】:

    标签: android


    【解决方案1】:

    与其尝试匹配哪个颜色由哪个字符串表示,不如自己传递资源ID?

    【讨论】:

      【解决方案2】:

      试试

      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));
      

      【讨论】:

        【解决方案3】:
        text.setText(Html.fromHtml("<font color='red'>R</font>"));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-18
          • 2013-02-23
          • 2011-10-04
          • 1970-01-01
          • 1970-01-01
          • 2023-03-11
          • 1970-01-01
          • 2013-02-10
          相关资源
          最近更新 更多