android - 约束布局的子边距

标签 android android-constraintlayout

我正在尝试在 constraintlayout 中使用两个 View 。但是一旦分配了边距, subview 就会出现未定义的行为。我们将不胜感激。

这是我的代码:

<android.support.constraint.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:src="@drawable/ic_action_google_play"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtNew"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="TextHere"
        android:textSize="24sp"
        app:layout_constraintLeft_toRightOf="@+id/img"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

最佳答案

在 ConstraintLayout 中,要在任何一侧(左、上、右、下)应用边距,必须显式定义该侧的约束。如果您的情况是,您希望 ImageView 的每一侧都有“16dp”边距,因此您需要为该 ImageView 的每一侧声明约束。您用 XML 编写了以下内容:

<ImageView   
    android:layout_margin="16dp"       
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

像这样替换:

<ImageView
    android:id="@+id/img"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="16dp"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
     />

要使 Right 和 Bottom 的边距起作用,您还需要添加以下内容:

    app:layout_constraintRight_toLeftOf="@+id/txtNew"
    android:layout_marginRight="16dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="16dp"

同样的事情也适用于 TextView。

关于android - 约束布局的子边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473386/

相关文章:

java - 如何在 ConstraintLayout 类中使用 android 扩展 XML 布局?

android - 获取 "Error: Missing Constraints in ConstraintLayout"

android studio新建项目看不到src文件夹

android - 如何在 Constraintlayout 中为 Barrier 指定边距

单一 View 中的Android图像和文本

android - 如何使用 SQLite 数据库存储来自 Web 的同步数据 - 线程安全

android - 如何在 ConstraintLayout 中以固定边距和动态宽度均匀放置 View ?

android - 如何删除约束布局中 View 之间的额外空间?

java - 选择文件路径未在android studio中转换为文件

Android 和使用领域