如何在 android 中将关闭按钮添加到 cardview 的右上角

how to add close button to top right to cardview in android

如何在 android 中将关闭按钮添加到 cardview 的右上角。 像这样: See this 我想将我的关闭按钮放在对话框的右上角,以便单击按钮时将 cardview 的可见性设置为消失。有更好的方法吗?

使用 FrameLayout,您可以通过调整关闭按钮视图的边距来实现这一点

您可以使用以下代码片段创建带有右上角外部关闭按钮的弹出窗口:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/dim_10"
    android:layout_marginTop="@dimen/dim_20"
    android:layout_marginRight="@dimen/dim_10"
    android:layout_marginBottom="@dimen/dim_20">

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dim_25"
            android:orientation="vertical"
            android:paddingStart="@dimen/dim_5"
            android:paddingTop="@dimen/dim_18"
            android:paddingEnd="@dimen/dim_5"
            android:paddingBottom="@dimen/dim_40">

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tv_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="@string/text_description"
                android:textColor="@color/color_black"
                android:textSize="@dimen/text_size_24"/>

        </androidx.cardview.widget.CardView>
    </androidx.appcompat.widget.LinearLayoutCompat>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/iv_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|top"
        android:background="@color/color_black"
        android:padding="@dimen/dim_5"
        android:src="@drawable/close_popup" />
</FrameLayout>