我有2个彼此相邻的按钮(链接),并且应用程序中可能有2种状态,或者在这种情况下,只有左按钮可见,在这种情况下应该水平居中,或者在两种情况下都可见应该水平居中。所有这些都有效,但是按钮中有多个单词,在小屏幕上,按钮都被剪切而不是环绕。要将此设置固定为两个按钮都可以将宽度设置为0dp,但是在这种情况下,按钮会变得尽可能宽,因此在较大的屏幕上或只有一个按钮可见时,它看起来不正确。我的问题是使用ConstraintLayout时如何将单词包装在按钮中?如何约束按钮,使它们正确缠绕并且不会变得比需要的宽度宽?使用LinearLayout可以立即使用,但我想使用ConstraintLayout。我尝试在两个按钮上都设置app:layout_constrainedWidth =“ true”,但是这样做不起作用,它将只包装第一个按钮,如果第二个按钮有足够长的文本,它将包装它不存在。
更新:在示例中,我将按钮文本更新为更长。
XML:
flatMap()
答案 0 :(得分:2)
在按钮中使用 a=[]
a.__class__
#<class 'list'>
并将宽度设置为app:layout_constraintWidth_default="wrap"
,而不是0dp
,如下所示:
wrap_content
当包含较大的文本(如问题中提供的文本)时,我已经使用<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button1"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintWidth_default="wrap"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Long text for first button"
app:layout_constraintEnd_toStartOf="@+id/button2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintHorizontal_weight="1"/>
<Button
android:id="@+id/button2"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintWidth_default="wrap"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="Long text for second button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/vertical_guideline_50_pc"
app:layout_constraintHorizontal_weight="1"/>
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/vertical_guideline_50_pc"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.5" />
</androidx.constraintlayout.widget.ConstraintLayout>
在按钮之间平均分配宽度。当其可见性处于Guideline
状态时,以编程方式将app:layout_constraintStart_toEndOf
中的Button2
从Guideline
更改为Button1
:
GONE
屏幕截图显示了问题中提供的较长文本,两个按钮都包裹在它们周围:
按钮2消失的屏幕截图:
答案 1 :(得分:0)
尽管SaadAAkash答案是正确的,但至少在androidx约束布局1.1.3中,layout_constraintWidth_default="wrap"
已过时,正确的方法如下:
layout_width="0dp"
替换为layout_width="wrap_content"
layout_constraintWidth_default="wrap"
替换为layout_constrainedWidth="true"
它应该产生相同的结果。