【问题标题】:Issues with multiline button texts ignoring button margins多行按钮文本忽略按钮边距的问题
【发布时间】:2020-07-13 13:02:59
【问题描述】:

基本上我有一个带有很长字符串的按钮,它会导致换行。按钮有左右边距,但是由于按钮占据了父级的整个宽度,因此多行按钮文本会忽略这些边距。

一个明显的解决方案是将布局宽度设置为 0dp,但这会强制使用静态宽度,这意味着对于较短的按钮文本,按钮不再被包裹。

有没有很好的解决方案如何保持 wrap_content 的宽度但仍然不忽略边距?

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android">

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:text="@string/longstring"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: java android button margin line-breaks


    【解决方案1】:

    在按钮 xml 中添加以下行,以便按钮尊重边距

    app:layout_constrainedWidth="true"
    

    输出

    【讨论】:

    • 这就是我要找的东西。后续问题:如何获得精确换行,因为自动换行可能不需要全宽但仍然使用它?
    • 很高兴我能帮上忙:)
    • 使用 android:layout_width="match_parent" 可能会有所帮助
    • 不幸的是,这只会将较小按钮的宽度增加到可用的全部宽度。
    • 那么我没有正确理解这个问题。请尽量详细一点。
    【解决方案2】:

    最简单的解决方案是您必须在按钮的字符串中使用 /n 以使按钮文本不扩展
    例如“这是一个字符串然后 /n 它将在下一行”

    这样我认为你的按钮不会忽略边距并显示里面的文字

    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="32dp"
            android:layout_marginRight="32dp"
            android:text="@string/longstring"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constrainedWidth="true" />
    
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    【讨论】:

      猜你喜欢
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多