【问题标题】:How to set a button with a text in android如何在android中设置带有文本的按钮
【发布时间】:2014-02-07 09:45:28
【问题描述】:
我有一个问题。是否可以制作一个具有 3 行文本的按钮。这是我的想法
|---------------|
|text1... |
|text2... |
|text3... |
|_______________|
但是我想放在按钮上的文本是从一个数组中接收的,并且它会动态变化。这是可行的还是有更容易的替代方法?
【问题讨论】:
标签:
android
arrays
button
text
【解决方案1】:
在按钮文本中使用“\n”创建新行
<Button
android:text="text1\ntext2\ntext3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
看起来像
【解决方案2】:
您可以像这样以编程方式在按钮上设置文本:
btn.setText("Text1\n"+"Text2\n"+"Text3");
或者你可以像这样直接在xml中设置:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1\nText2\nText3"/>
【解决方案3】:
如果您尝试在布局 XML 文件中添加新行:
使用&#10;(换行)
android:text="Hi Hello"
如果您尝试在代码中添加新行,只需使用 '\n',就像在任何其他文本中一样。
如果您看不到第二行,则可能是您的 Button 没有足够的高度。 IE,在我的例子中,包含按钮的布局有一个固定的高度,恰好使我的按钮完美地显示了一行文本。
第二种方法:
1) 在 ../res/values/strings.xml 中定义:
<string name="multilines">Line1Line1\nLine2Line2</string>
2) 在布局文件中引用:
<Button
android:id="@+id/btn_multilines"
android:text="@string/multilines"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
</Button>
动态:
button.setText("Line1\nLine2\nline3"); //button is the Button of id "btn_multilines"