如何阅读文本文件并在文本视图中显示?

时间:2018-06-13 17:13:05

标签: java android

当我导航到应用程序中的某个页面时,我希望显示文本文件中的文本,但不是。我错过了什么吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_content);

    Button backButton = findViewById(R.id.button_back);
    Button selectAnotherButton = findViewById(R.id.button_select_another);

    TextView contentText = findViewById(R.id.content_text);
    String text = "";

    try {
        // file to inputstream
        InputStream input = getAssets().open("jokes.txt");
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();
        // byte buffer into a string
        text = new String(buffer);

    } catch (Exception e) {
        System.out.println(e);
    }

    contentText.setText(text);
}

2 个答案:

答案 0 :(得分:0)

上面的代码很好,它按预期工作。无法看到文本的原因是因为文本视图布局重叠了textview布局,所以我看不到文本

答案 1 :(得分:0)

contentText.invalidate();
contentText.requestLayout();