Android中的CardView不遵守ConstraintLayout的约束

问题描述 投票:1回答:3

我正在尝试在ConstraintLayout中放置一个CardView,两边都有一个特定的边距。

我将CardView边距与父节点相比设置为左右两边,然后将layout_width设置为0dp:它将扩展并占用所有可用空间,忽略边距。

相反,如果我将CardView放在FrameLayout中,然后将相同的精确约束应用于FrameLayout,则FrameLayout将尊重它们并且CardView将恰好适合它(参见下面的代码)。

<android.support.constraint.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="...MyActivity...">
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        app:layout_constraintBottom_toTopOf="@+id/nextButton"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.v7.widget.CardView>
           <...omitted...>

所以我按照我需要的方式工作,但我想了解为什么在计算自己的宽度时,CardView没有考虑边距,设置为0dp。

android android-cardview cardview android-constraintlayout
3个回答
0
投票

在CardView中,从侧面设置距离,您可能会看到以下示例:

<android.support.v7.widget.CardView
    android:layout_width="0dp"
    android:layout_height="186dp"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:layout_marginTop="8dp"
    android:alpha=".5"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardBackgroundColor="@android:color/black"
    app:cardCornerRadius="4dp"
    app:constraintSet="@dimen/spacing_normal"
    app:contentPaddingBottom="@dimen/spacing_double"
    app:contentPaddingTop="@dimen/spacing_double"
    app:elevation="@dimen/cardview_default_elevation"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_constraintLeft_creator="1"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintTop_creator="1" />

请告诉我结果


0
投票

它无法工作的原因是它需要layout_marginEnd和layout_marginStart而不是layout_marginLeft和layout_marginRight。

这些似乎默认添加到FrameLayout但不添加到CardView。


0
投票

我找到了一种方法来完成这项工作,而无需添加其他视图。您只需要在onStart或onCreateView方法中添加以下行:

getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

如果您想知道为什么会这样,那是因为DialogFragment采用布局的父视图(在本例中是您的ConstraintLayout)并将其宽度和高度设置为wrap_content。这会覆盖它。

© www.soinside.com 2019 - 2024. All rights reserved.