1

In android, a String resource can be created in XML by using

<string name="name">data</string>

to create a new line, \n may be used. However, if the user personally inputs data into an EditText and includes a \n, the writing is saved to a String and when the writing is displayed again in a TextView the result would be something such as:

Line 1\nLine2

How come the \n doesn't apply to user written Strings?

The end goal for me is to be able to have the user type a \n into a String to make sure the String is displayed in multiple lines.

How would this be achieved? Thanks in advance!

1
  • try to set android:maxLines="4" in textView layout Commented Oct 11, 2015 at 20:42

4 Answers 4

2

Use this :

TextView view = your text view;
view.setSingleLine(false);

view.setText("first line" + "\n" + "second line" + "\n" + "third line");
Sign up to request clarification or add additional context in comments.

4 Comments

What would be the best way to split the string at the \n? Should using just a basic .split() work?
I will have to try this out later. Thanks for the response.
@26hmkk No problem. Vote it up if it helps.
Thanks for all your help!
1

How are you doing setText() in the textView.

Try this...

TextView view = your text view;
view.setSingleLine(false);
view.setText("first line\n"+"second line\n"+"third line");

Comments

1

with

System.getProperty("line.separator")

you get a String which results in a new line. I would replace \n by this expression.

Comments

1

The text entered in an input field is used as an actual text. That means, when the user enters the Hello \n World and the code calls getText().toString(), what will actually be returned is: Hello \\n World that means, it's the actual slash symbol and not the "carriage return" symbol.

I don't believe android has any built-in API to give you the actual code typed by the user, that means, that you have to write that code yourself. If all you need is the \n as a carriage return it is simple:

getText().toString().replace("\\n", "\n");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.