【问题标题】:Not well formed text in TextView after append()append() 后 TextView 中的文本格式不正确
【发布时间】:2019-06-19 21:26:22
【问题描述】:

我的 TextView 有问题。我以前没有见过这个问题,谷歌也没有帮助。 我有 TextViews 和文本,它们像字符串资源一样在 xml 中定义。

<?xml version="1.0" encoding="utf-8"?>
...
    <TextView
        android:id="@+id/TVName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="@string/name"
        android:textSize="@dimen/textViewTextSize"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:textAllCaps="true"
        android:layout_marginEnd="@dimen/marginBetweenTextViewsEnd"
        android:background="@color/gray41"
        />
...

在我的代码中,我正在为此 TextView 执行 append()

public class Page extends AppCompatActivity {
    TextView TVName;
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_profile);
        TVName = findViewById(R.id.TVName);
        TVName.append(" " + "danya");
}
}

字符串.xml

<resources>
    <string name="name">Name:</string>
</resources>

我得到了一些象形文字,而不是NAME: danya,或者只是像“NAME:3ô”这样的垃圾

首先,我使用 Retrofit 从服务器获取 append() 的文本,并认为这是来自服务器的格式错误的文本,但当我尝试上面的代码时,问题再次出现。

当我在 setText() 上更改附加时 - 一切正常。

我也尝试过在 android:text="Name:" 这样的文本上更改 xml 中的字符串资源,但同样的问题。

所有文件一如往常以 UTF-8 编码且未手动编码。

【问题讨论】:

    标签: android string textview append


    【解决方案1】:

    更好的解决方案是在您的string.xml 中包含这样的字符串:

    <resources>
        <string name="name">Name: %s</string>
    </resources>
    

    然后,不用在 xml 中设置该字符串,只需以编程方式设置它:

    TVName = findViewById(R.id.TVName);
    String formattedName = String.format(getResources().getString(R.string.name), "danya");
    TVName.setText(formattedName);
    

    这里很好地解释了String::format 以及可用于传递不同数据格式的所有参数:https://dzone.com/articles/java-string-format-examples

    【讨论】:

    • 找到了解决方案并尝试了您的代码String STVName = String.format(TVName.getText().toString(), " ", "danya"); 并得到了Name: - 为什么?
    • 您不应该将空格作为参数,因为它已经在您的字符串资源中。 R.string.name 中的%s 表示一个参数(即"danya")。字符串中已经有一个空格Name: %s :) 你需要做的就是写String.format(getResources().getString(R.string.name), "danya");
    • 你是对的,一切正常。谢谢你的好建议。
    • @danyapd 这是一篇关于 String.format 及其工作原理的文章:mobikul.com/string-placeholders-formatting-strings-android 希望它能帮助您更好地理解它:)
    【解决方案2】:

    我试图删除 textAllCaps 属性并且...它有效。我认为 append 不适用于 textAllCaps。 但我的代码需要大写,所以我的解决方案是:

    String getSTVName = TVName.getText().toString();
    String STVName = String.format(getSTVName, "danya");
    TVName.setText(STVName);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多