簡體   English   中英

如何在單擊添加按鈕時在現有卡片視圖下方添加卡片視圖?

[英]How to add a cardview below of an existing cardview on click of add button?

我需要在單擊此添加按鈕時添加一個 cardview,該 cardview 必須低於前一個並且添加按鈕應位於新卡片視圖下方的 go

在此處輸入圖像描述

你可以這樣做:

activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.cardview.widget.CardView
            android:id="@+id/baseCard"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_margin="8dp"
            app:cardBackgroundColor="@color/colorAccent"/>

        <Button
            android:id="@+id/butAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:text="Add" />

    </LinearLayout>

</ScrollView>

在您的布局文件中,您有 ScrollView 和 ScrollView 內部的 LinearLayout。 向 LinearLayout 添加一個 CardView 和 Button。 現在您必須添加 onClick 偵聽器。 所以在 onCreate 你這樣做:

butAdd.setOnClickListener {
    val newCardView = CardView(this) // creating CardView
    newCardView.layoutParams = baseCard.layoutParams //setting params like 1st CardView
    root.addView(newCardView, root.childCount - 1) // adding cardView to LinearLayout at the second to last position
}

結果(添加2個CardView后,藍色的是xml中第一個定義的):

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM