cg-algo
cg-algo

Reputation: 79

Add many CardViews with onclick method programmatically

I'm still new to the Android and I want to add a CardView to the activity each time a button is clicked. The CardView has text on it and a background image. I already have the XML file that can add this, but because I want to be able to add more than one, I can't use <include.>. The first image is when the button is clicked once and the second is when the button is clicked 3 times. I already have the onClick for the TextView that says "Click To Add Block" and the XML for the CardView, but I can't make it so that you can add them and change the text in the TextView in each and every one of them. I also can't seem to find a way to programmatically add an onClick listener to the programmatically created CardView. Later down the line, I would also like to be able to delete the CardView from a click of a button too.

After Button Clicked Once

After Button Clicked 3 Times

Here is the CardView XML file (Before it was inside a Relative Layout)

<androidx.cardview.widget.CardView
    android:id="@+id/cardviewClassesBlock1"
    android:layout_width="330dp"
    android:layout_height="75dp"
    android:layout_marginTop="90dp"
    android:layout_centerHorizontal="true"
    app:cardCornerRadius="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ic_launcher_background">

        <TextView
            android:id="@+id/textviewClassesBlock1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="3dp"
            android:textSize="22sp"
            android:fontFamily="@font/amiko_semibold"
            android:textColor="@color/white"
            android:text="Block A"/>

        <ImageView
            android:layout_width="60dp"
            android:layout_height="6dp"
            android:layout_marginStart="10dp"
            android:layout_below="@+id/textviewClassesBlock1"
            android:background="@drawable/rounded_corner_edittext" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="5dp"
            android:textColor="@color/white"
            android:text="P - 0 | T - 0 | A - 0"/>

    </RelativeLayout>

</androidx.cardview.widget.CardView>

Upvotes: 2

Views: 927

Answers (1)

iknow
iknow

Reputation: 9892

I have created a sample project for You.

  1. First You have to create a layout for Your CardView. In res/layout create card_base.xml. In this layout add:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardviewClassesBlock1"
    android:layout_width="wrap_content"
    android:layout_height="75dp"
    android:layout_centerHorizontal="true"
    app:cardCornerRadius="10dp"
    android:layout_margin="10dp"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ic_launcher_background"
        >

        <TextView
            android:id="@+id/textviewClassesBlock1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="3dp"
            android:text="Block A"
            android:textSize="22sp"
            />

        <ImageView
            android:layout_width="60dp"
            android:layout_height="6dp"
            android:layout_below="@+id/textviewClassesBlock1"
            android:layout_marginStart="10dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="5dp"
            android:text="P - 0 | T - 0 | A - 0"
            />

    </RelativeLayout>

</androidx.cardview.widget.CardView>

This is basically Your CardView with small changes.

  1. Next, in Your activity_main.xml add this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    >

    <Button
        android:id="@+id/butAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add New Card"
        />

    <Button
        android:id="@+id/butDoSth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Do something"
        />

    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/cards"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <include
            android:id="@+id/includedLayoutFirst"
            layout="@layout/card_base"
            />

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.appcompat.widget.LinearLayoutCompat>

This is a starter (very simple) look of Your app. It has one button and one CardView which is already inserted.

  1. Now in Your MainActivity.java paste this:
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.cardview.widget.CardView;

public class MainActivity extends AppCompatActivity
{
    private int starter = 66; //ASCII code for `B`
    LinearLayoutCompat cards;
    Button buttonAdd;
    Button buttonDoSth;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        cards = findViewById(R.id.cards);
        buttonAdd = findViewById(R.id.butAdd);
        buttonDoSth = findViewById(R.id.butDoSth);

        buttonAdd.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                CardView newCard = new CardView(MainActivity.this);
                getLayoutInflater().inflate(R.layout.card_base, newCard);

                TextView t = newCard.findViewById(R.id.textviewClassesBlock1);

                String current = Character.toString((char) starter++);

                t.setText("Block " + current);
                newCard.setTag(current); //

                cards.addView(newCard);
            }
        });

        buttonDoSth.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                findBlockAndDoSomething("B");
            }
        });
    }

    private void findBlockAndDoSomething(String name)
    {
        Log.d("MyTAG", "CLICK");

        for (int i = 0; i < cards.getChildCount(); i++)
        {
            CardView selected = (CardView) cards.getChildAt(i);

            if (selected.getTag() != null && selected.getTag().toString().equals(name))
            {
                // do something. E.g change block name
                TextView textViewClassesBlock1 = selected.findViewById(R.id.textviewClassesBlock1);
                textViewClassesBlock1.setText("Block XXX");
                return;
            }
        }
    }
}

Result (starter code and with adding new CardView):

enter image description here

Upvotes: 1

Related Questions