48

My button's layout_width set to match_parent.

In order to display multi lines on the button, I tried:

  • insert '\n' into the text on button

  • set Singleline false set Maxlines to 2 or 3

  • convert html from Html.fromHtml

Nothing worked. '\n' showed up as a small square on the button while showing single line of text.

Does anybody have any idea why this is happening and how I can fix this?

UPDATE: I just found out I was using custom button that has its own text drawing. That's the reason. Sorry for the confusion. I just punished myself by banging my head.

1
  • I have same issue with a simple TextView
    – Borzh
    Apr 2, 2015 at 18:33

3 Answers 3

88

If you're trying to add a new line in a layout XML file:

Use 
 (new line)

    android:text="Hi
Hello"

If you're trying to add a new line in code, just use '\n', same as in any other text.

If you can't see the second line, it may be that your Button doesn't have enough height. IE, in my case, the layout containing the button had a fixed height that just happened to make my button perfectly display one line of text.

3
  • 1
    use \n in strings.xml Sep 19, 2017 at 11:19
  • 2
    and how can you change their fonts? or make the 'Hi' look larger than 'Hello'?
    – Nav Nav
    Feb 6, 2019 at 18:07
  • What if I need different fonts and size for each line of text, and also an icon on top-center above the lines? ;-)
    – TomeeNS
    Aug 3, 2022 at 20:47
28

I just tried and it worked:

1) Define in ../res/values/strings.xml:

<string name="multilines">Line1Line1\nLine2Line2</string>

2) Refer it in the layout file:

<Button
    android:id="@+id/btn_multilines"
    android:text="@string/multilines"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent">
</Button>
0
1

In case you want to do that programmaticaly you can use System.getProperty("line.separator") in the string to change lines. Like this:

String mybuttontext=line1+System.getProperty("line.separator")+line2;

and then set this String as buttons text.

Your Answer

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

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