0

I am creating one tutorial and for that i want to set text for text view. I know we can set text by textView.setText("your stuff") but my text is too large and it looks awkward in java file. So is there any other efficient way of doing it?

Thanks for your help

4 Answers4

4

Place it in string resources

<string name="long_string">
  Very long string
</string>

Access it in java

TextView textView = (TextView)findViewById(R.id.my_text);
textView.setText(R.string.long_string);

You can check CHARACTERS TO ESCAPE IN XML DOCUMENT incase you have them in text content

Community
  • 1
  • 1
Emmanuel Mtali
  • 4,383
  • 3
  • 27
  • 53
1

The other answers have already suggested putting it in a string resource. As an alternative to that, you can also put it under res/raw and read it like a regular text file.

Example:

res/raw/looooong.txt

This is some looooooooooooooooooooooooong text.
You can even put them in separate lines.
Just make sure to handle reading the newline characters.

TextView

textView.setText(readRawResource(context, R.raw.looooong));

readRawResource

private String readRawResource(Context ctx, int resId)
{
    InputStream inputStream = ctx.getResources().openRawResource(resId);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    StringBuilder sb = new StringBuilder();
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
    } catch (IOException e) {
        return null;
    }
    return sb.toString();
}
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
0
textView.setText(" AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC 
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");

OR

Read it from a file like this

for (String line : Files.readAllLines(Paths.get("/path/to/file.txt")))
{
  // ...
}

Save the output in a string, Then just show it using textView.setText("x");

for more information , read this

EDIT

You will need to learn about ScrollView or HorizontalScrollView if your text is more than the size of the screen. Also use this , don't forget to set a string ID for the textView.

Community
  • 1
  • 1
Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30
0

Im not sure I understood but if its the length in the file what bothers you you can set your string in the strings resource file res/values/string.xml This way: your stuf Then in your Code set the string as follows: textView.setText(getResources().getString(R.string.my_string));

Marco Pierucci
  • 1,125
  • 8
  • 23