单击添加按钮时如何在现有卡片视图下方添加卡片视图?

问题描述

我需要点击此添加按钮添加卡片视图,并且卡片视图必须位于前一个卡片视图的下方,并且添加按钮应该位于新卡片视图的下方

enter image description here

解决方法

您可以这样做:

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个CardViews之后,蓝色的是xml中的第一个定义):

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...