Java android:使用TextView附加换行符

max*_*ins 17 java android newline textview

我只是想以某种方式在我的线性布局中添加一个新行:

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);
Run Code Online (Sandbox Code Playgroud)

但这只是增加了几个空格.有人可以帮我吗?谢谢.

ina*_*ruk 30

首先,你需要让你TextView成为多线.然后使用简单的"\n"字符串进行换行.

final TextView nline = new TextView(this);
nline.setSingleLine(false);
nline.setText("first line\n"+"second line\n"+"third line");
Run Code Online (Sandbox Code Playgroud)


Max*_*mus 19

如果您只想在两个其他视图之间有一些空白空间,可以在XML中执行此操作(假设您使用XML进行布局).像这样的东西可以工作,基本上放入一个透明背景和给定高度的视图.这假设您在TextView中有任何您想要的参数.

<TextView />

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

<TextView />
Run Code Online (Sandbox Code Playgroud)

另外,在你上面尝试的内容中......你可以尝试一个空格和换行符...这可能有效.

nline.setText(" \n");
Run Code Online (Sandbox Code Playgroud)

  • 有趣的是,没有其他人在'\n'之前提到空间,感谢Maximus :) (2认同)