【问题标题】:How to change color of unicode character in TextView?如何在 TextView 中更改 unicode 字符的颜色?
【发布时间】:2016-08-11 14:08:24
【问题描述】:

'来自维基百科的this 链接我得到了红色心脏的代码,并希望在我的TextView 中显示以生成自定义表情符号,但为什么它总是显示黑色插入红色 U+2665 的颜色在维基百科。下面是我的代码

  TextView tv=(TextView)findViewById(R.id.testText);

 //  tv.setText(Html.fromHtml("\u2665"));



tv.setText(Html.fromHtml("<font color='red'>"+"\u2665"+"</font>"));

没有让它变成红色,它仍然是黑色,如果我输入任何其他文本,它会显示红色。

【问题讨论】:

  • 字体没有关于颜色的信息......它们总是在字体的颜色颜色中
  • 我认为您只需更改文本颜色:Html.fromHtml("\u2665")
  • 将您的 unicode 转换为十六进制并像这样使用它。 tv.setText(Html.fromHtml("♥"));
  • @Selvin 请查看我的编辑并建议我

标签: android unicode textview


【解决方案1】:

解释: TextView 字体将其呈现为表情符号,这意味着它基本上使用预定义的图像,因此在这些上忽略字体颜色。有一个 unicode 字符可以用作后缀,告诉字体使用文本变体(VARIATION SELECTOR 15, "\uFE0E", use like this:"\u2665\uFE0E" ),但显然 Android 确实忽略了这些,至少在我的手机上(Samsung SM-G800F with 5.1.1)

股票浏览器和 chrome 也无法识别变体选择器,而 Firefox for Android 可以在我的手机上运行。

显然这是不同的手机,你可以在related question on Stackexchange UX中看到


解决方案: 为我解决了这个问题的方法是手动为 TextView 设置另一个 ttf 字体,它支持这些字符但不支持表情符号,即来自 GNU FreeFont Project 的 FreeSans。

下载字体并将其放入 src/assets/fonts. 然后设置 TextView 的字体:

    Typeface type = Typeface.createFromAsset(getAssets(),"fonts/FreeSans.ttf");
    mTextView.setTypeface(type);

您应该适当地将字体加载到静态常量中,以避免一遍又一遍地重新创建它。

【讨论】:

  • 该字体在我的 S8+ 7.0 上不起作用(默认为 Roboto)。还有其他没有表情符号的字体吗?
【解决方案2】:

要使其变为红色,您必须将其设置为 textColor RED。像这样 ->

TextView tv=(TextView)findViewById(R.id.testText);
tv.setText(Html.fromHtml("\u2665"));
tv.setTextColor(Color.RED); // Set color here

【讨论】:

    【解决方案3】:

    将您的unicode 转换为Hexadecimal 并像这样使用它。 tv.setText(Html.fromHtml("&amp;#x2665;"));

    查看我的answer 了解更多信息。

    【讨论】:

      【解决方案4】:

      您还可以在文本视图中的 xml 文件中设置颜色,例如 ..

      <TextView
                  android:id="@+id/tv_id"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_gravity="center"
                  android:layout_margin="@dimen/margin_5"
                  android:textColor="@color/white"
      />
      

      并在 java 文件中设置文本自定义表情符号,它的工作正常。

      【讨论】:

      • @theUtrun 没有必要将 unicode 更改为十六进制。
      【解决方案5】:

      红心使用代码\u2764

      它对我有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-26
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多