Android按钮长文本换行失效求助:使用 无效,附截图
Hey there! I’ve dealt with this exact frustration before—trying to get line breaks in button text using in your strings.xml only to see it show up as a single line. Let’s walk through the reliable fixes that’ll get your button text wrapping properly:
First, double-check your
strings.xmlsyntax
Make sure your string is defined correctly without extra spaces or formatting issues. It should look like this:<string name="multi_line_btn">First Line Second Line</string>Avoid adding spaces around
unless you want extra spacing between lines.Enable multi-line support in your Button’s layout attributes
By default, Android Buttons are set to single-line display. Add these attributes to your Button in the layout XML to allow wrapping:<Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/multi_line_btn" android:singleLine="false" android:maxLines="2" <!-- Adjust to the number of lines you need --> android:gravity="center" <!-- Centers text vertically/horizontally --> />The
android:singleLine="false"is the critical one here—it tells the system not to truncate text to a single line.If layout settings still fail, set the text programmatically
Sometimes referencing the string directly in the layout doesn’t trigger the line break correctly. Try setting the text in your Activity/Fragment code instead:// Kotlin val myButton = findViewById<Button>(R.id.my_button) myButton.text = getString(R.string.multi_line_btn)// Java Button myButton = findViewById(R.id.my_button); myButton.setText(getString(R.string.multi_line_btn));Check your Button’s width
If your Button usesandroid:layout_width="wrap_content", it might not have enough horizontal space to wrap the text. Switch tomatch_parentor set a fixed width to give the text room to break into multiple lines.
These steps should resolve the issue 9 times out of 10—they’ve worked for me and countless other Android devs facing the same problem.
内容的提问来源于stack exchange,提问作者Satvik Sabharwal

