【问题标题】:How to add a cardview below of an existing cardview on click of add button?单击添加按钮时,如何在现有卡片视图下方添加卡片视图?
【发布时间】:2020-12-18 05:19:55
【问题描述】:

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

【问题讨论】:

  • 添加按钮只能添加一张卡片还是可以无限添加卡片视图?
  • 点击添加按钮时是否要添加另一个卡片视图?
  • 是的,当单击添加按钮时,我想在其下方添加另一个卡片视图

标签: android android-studio android-layout angular-material android-cardview


【解决方案1】:

你可以这样做:

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中第一个定义的):

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多