19

I just want to add a new line somehow to my linear layout:

layout = (LinearLayout) findViewById (R.id.layout);  

... //some other code where I've appended some strings already

final TextView nline = new TextView(this);
nline.setText(Html.fromHtml("<br>")); //i also tried:  nline.setText("\n");
layout.addView(nline);

But this just adds a few spaces. Can someone help me out? Thanks.

1
  • 1
    nline.setText(Html.fromHtml("<br>")); will be work correct if you add nline.setSingleLine( false);
    – Tapa Save
    Apr 21, 2014 at 9:19

5 Answers 5

32

First you need to make your TextView to be multiline. And then use simple "\n" string for linebreak.

final TextView nline = new TextView(this);
nline.setSingleLine(false);
nline.setText("first line\n"+"second line\n"+"third line");
1
  • What if it is \n\n ? In this case everything else after that is being cut off.
    – Zon
    Oct 10, 2018 at 4:46
20

If you just want to have some empty space between two other views, you could do this in your XML (assuming you're using XML for the layout). Something like this could work, basically putting in a View with a transparent background and given height. This is assuming you have whatever parameters you want in your TextViews.

<TextView />

<View android:background="#00000000"
      android:layout_height="12dp" //or whatever density pixel height you want
      android:layout_width="fill_parent" />

<TextView />

Also, in what you tried above... you could try a space and newline... that might work.

nline.setText(" \n");
1
  • 2
    interesting, that nobody else mentions the space before the '\n', thanks Maximus :)
    – jpm
    Aug 28, 2013 at 11:05
4

You may need to set the InputType to TYPE_TEXT_FLAG_MULTI_LINE using the setInputType() method of TextView

tv.setInputType(tv.getInputType()|InputType.TYPE_TEXT_FLAG_MULTI_LINE);

You also could just set some margin/padding on the other views. I think that TextViews should not be misused as spacers.

0

Simple as:

String hello = getResources.getString(R.string.hello);
String world = getResources.getString(R.string.world);
textView.setText(hello + "\n" + world);
0

Simple by giving "\n" data is displayed in a new line

txtView.setText("Latitude :" + latitude + "\nLongitude :" + longitude);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.