Android:实现单行等宽双Button并完整显示文本的问题求助
Got it, let's fix this issue where you need two buttons with equal widths, fully visible text, and the smallest possible overall footprint. The problem with your current approach is that wrap_content lets each button size itself to its text, leading to mismatched widths—while forcing maxLines="1" risks truncating text.
Here's the most reliable way to achieve what you want using ConstraintLayout:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gap="8dp"> <!-- Optional gap between buttons for better spacing --> <Button android:id="@+id/button_sample" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Sample text" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> <Button android:id="@+id/button_extra" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Extra text" app:layout_constraintStart_toEndOf="@id/button_sample" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_toMatchWidth="@id/button_sample"/> </androidx.constraintlayout.widget.ConstraintLayout>
How this works:
- The first button uses
wrap_contentto size itself exactly to its text ("Sample text"). - The second button uses
0dpfor width andlayout_constraintWidth_toMatchWidth="@id/button_sample"to force it to match the first button's width. This ensures both buttons are identical in width, even though their text lengths differ. - The parent
ConstraintLayoutuseswrap_contentfor width, so it only takes up the space needed to fit both buttons side-by-side—no extra wasted space. - All text stays fully visible because we're not restricting
maxLinesor truncating anything.
If you prefer using LinearLayout instead, you can do this (though it's slightly less flexible):
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="2" android:gap="8dp"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Sample text"/> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="Extra text"/> </LinearLayout>
This works because layout_weight="1" splits the available width of the parent LinearLayout equally between the two buttons. Since the parent is wrap_content, it will expand just enough to fit the widest button's text (after splitting), ensuring both buttons are the same width and all text is visible.
Either approach will meet your requirements—pick the one that fits your existing layout setup best!
内容的提问来源于stack exchange,提问作者CoolMind

