【发布时间】:2020-03-06 21:42:19
【问题描述】:
我有 2 个彼此相邻的按钮(链接),并且应用程序中有 2 种可能的状态,要么只有左侧按钮可见,在这种情况下它应该水平居中,要么两者都可见,在这种情况下它们都可见应该水平居中。这一切都有效,但是按钮中有多个单词,并且在小屏幕上,按钮都被剪裁而不是换行。要修复此设置,将两个按钮的宽度设置为 0dp 可以正常工作,但在这种情况下,按钮会变得尽可能宽,因此在较大的屏幕上或只有一个按钮可见时,它看起来不正确。我的问题是如何在使用 ConstraintLayout 时将单词包装在按钮中?如何约束按钮,使它们正确包裹并且不会变得比需要的宽?使用LinearLayout,这一切都是开箱即用的,但我想使用ConstraintLayout。我尝试在两个按钮上设置 app:layout_constrainedWidth="true" 但这不起作用,它将只包装第一个按钮,如果第二个按钮有足够长的文本,它将不存在。
更新:我将示例中的按钮文本更新为更长。
XML:
<Button
android:id="@+id/button1"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Long text for first button"
app:layout_constraintEnd_toStartOf="@+id/button2"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/objectAboveButtons"
app:layout_goneMarginEnd="0dp"
app:layout_goneMarginRight="0dp" />
<Button
android:id="@+id/button2"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:text="Long text for second button"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/button1"
app:layout_constraintTop_toBottomOf="@+id/objectAboveButtons" />
【问题讨论】:
-
很难说哪里出了问题,因为我试图复制这段代码,它的工作方式就像你需要的那样,只是约束几乎没有变化。
-
我匿名化了文本,也许“按钮 1 的文本”有点短,如果你让它长一点,它会左右剪辑,至少在我的三星 Galaxy s4 上是这样。
-
所以需要让文本进入第二行等等?我检查了一些答案。您可以以编程方式设置文本,包括
\n以使宽度正确。 -
是的,例如,如果 layout_width 为 0dp,则单词会在需要时自动换行,并且两个按钮的宽度相同,但这种方法的问题在于这些按钮将占用所有可用空间,而不是仅按需要的宽度。我希望按钮可以根据需要扩展,但不要超出它们的需要。我不确定以编程方式设置
\n,因为如果不需要,它不应该换行。 -
如果您可以指定所需的宽度,然后将其应用于按钮文本,它将起作用。因为唯一改变的是文本,并且只有当
getWidth()更大以至于它可以容纳时。我知道,这不是一个优雅的解决方案。但如果你试一试:)
标签: android android-layout android-constraintlayout