【问题标题】:How to format text coming from a text file to a textview in Android如何将来自文本文件的文本格式化为Android中的文本视图
【发布时间】:2017-09-03 21:43:43
【问题描述】:

我有一个使用文本文件来获取文本的应用程序。我可以通过从文件中读取并将其附加到 textview 来获取文本并将其放入 Textview 并且效果很好,但我想为文本添加格式。比如让标题加粗等等。

private void openFile()
{
    String tema = "Message";
    TextView temas = (TextView) findViewById(R.id.tutorial);
    temas.setText(title);
    temas.setTextSize(25);

    temas.setTextColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
    try {
        InputStream is = getAssets().open("tutorials/tutorial1.txt");
        int size = is.available();

        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        String text = new String(buffer);


        TextView tv = (TextView) findViewById(R.id.text);
        tv.setText(text);
        tv.setTextSize(20);
        tv.setTextColor(Color.parseColor("#000000"));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

【问题讨论】:

    标签: android file textview


    【解决方案1】:

    您可以使用html标签来显示格式化文本。例如

     String x ="Hello <b>World!</b>";
     rextView.setText(x);
    

    有关更多信息,请参阅此答案 here

    如果您知道要格式化哪个单词,则可以迭代字符串,直到找到该单词/字符添加标记并将其添加回字符串。另一种方法是在您要在文件本身中格式化的那个词之前添加特殊字符,例如,如果我想让我的标题变粗,那么我可以在那个词之前添加一个像“#”这样的字符,所以当我阅读文件时我知道我必须将哪种格式应用于哪个单词。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2021-06-23
      相关资源
      最近更新 更多