[英]How to add a cardview below of an existing cardview on click of add button?
你可以這樣做:
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.