【问题标题】:TextView ignores left and right marginsTextView 忽略左右边距
【发布时间】:2020-09-22 16:45:48
【问题描述】:

我的布局包括:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnFindPOIs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:text="Find POIs"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnGetLocation" />

    <TextView
        android:id="@+id/txtPoiDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnFindPOIs" />

</androidx.constraintlayout.widget.ConstraintLayout>

当 TextView 的内容超出一行时,它会正确地流到第二行,但文本会向右延伸到屏幕边缘,忽略 16dp 左右边距。

【问题讨论】:

    标签: android layout textview


    【解决方案1】:

    Layout Margin 影响 View 对象,在本例中为 TextView。不是对象内的实际文本。所以它仍然会紧贴物体的边缘。 我建议使用填充,它会直接影响文本。您可能还想考虑为对象添加重力?

    我还建议在这些视图上使用布局权重,否则您将遇到调整大小的问题!

    android:paddingStart="16dp"
    

    干杯!

    【讨论】:

    • 谢谢。填充有效,但我不明白为什么。据我了解,marginStart 规定了 TextView 与其父级(屏幕)之间允许的空间,而 padding 规定了 TextView 内部边缘和内容之间允许的空间。那么,为什么在我的原始布局(隐式零填充)中,文本不会停在距屏幕边缘 16dp 的 TextView 的边缘?
    • 啊,这很可能是由您的宽度属性引起的。您已将其设置为 wrap_content。这通常会忽略约束和边距。而是尝试将其设置为 match_constraint aka 0dp。通常最好在宽度上使用 match_constraint 或 match_parent。您始终可以通过使用 Space 并在水平线性布局内嵌套两个空格 + 一个文本视图来强制空间,然后使用布局权重。嵌套权重被认为是不好的做法,但您可以这样做。
    猜你喜欢
    • 1970-01-01
    • 2016-12-07
    • 2016-09-29
    • 1970-01-01
    • 2013-11-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多