如何将文本文件中的文本格式化为Android中的textview

时间:2017-04-08 15:55:58

标签: android file textview

我有一个使用文本文件来获取文本的应用。我可以通过从文件中读取文本并将其附加到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);
    }

}

1 个答案:

答案 0 :(得分:0)

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

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

了解更多信息,请参阅此答案 here

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