Search code examples
javaandroidandroid-studioandroid-layoutcardview

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


HOw to Add close button to top right to cardview in android. like this: See this i want to place my close button to the top right corner of the dialog so that the when button clicked thi will set the visibilty of cardview to gone. any better method to do this ?


Solution

  • You can create popup with top-right outside close button using below code snippet:

    <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>