在Android开发中,TextView是用于显示文本的基本UI组件。换行符是控制文本换行显示的特殊字符,常用的换行符包括\n
(换行)和\r\n
(回车+换行)。
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一行\n第二行\n第三行"/>
Java示例:
TextView textView = findViewById(R.id.textView);
textView.setText("第一行\n第二行\n第三行");
Kotlin示例:
val textView = findViewById<TextView>(R.id.textView)
textView.text = "第一行\n第二行\n第三行"
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml("第一行<br>第二行<br>第三行"));
在res/values/strings.xml
中:
<string name="multiline_text">第一行\n第二行\n第三行</string>
然后在代码中引用:
textView.setText(R.string.multiline_text);
android:maxLines
属性限制最大行数android:singleLine="false"
确保TextView支持多行显示(已弃用,推荐使用android:maxLines
)问题: 添加了\n
但没有换行效果
可能原因及解决方案:
singleLine="true"
- 改为false
或使用maxLines
wrap_content
\n
被转义 - 检查字符串是否正确包含换行符对于动态生成的文本,可以使用StringBuilder构建多行文本:
StringBuilder builder = new StringBuilder();
builder.append("第一行").append("\n");
builder.append("第二行").append("\n");
builder.append("第三行");
textView.setText(builder.toString());
在Kotlin中可以使用更简洁的方式:
textView.text = """
|第一行
|第二行
|第三行
""".trimMargin()
没有搜到相关的文章