how to programmatically add clickable item in a scrollview?

Issue

I’ll try my best to make it clear.

I’m trying to create a scrollview of item (let’s say it’s a shop) which I (the user) add by my self VIA the interface of the app AND can then modify by clicking on it inside the scrollview.
For example, my main page contains a button and the list of items. When I click on it it opens a dialog which asks me informations of the item I want to add. When I finished configuring the item, I’m back on the main page and I can see the item I just added and i can click on it to modify it if I need to.

What I struggle with here is the fact, in a scrollview we have to add views. Even if I know how to do it via java, how can I add, for each new item, a clicklistener ? how do I set the id for each new view (items) considering the fact that I only can set int ids ? etc.

Does someone knows any way to do what I try to ? I’ll make a very simple example of code and interfaces screenshot here in order to be very clear.

My XML MainPage : "activity_main.xml"

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <Button
            android:id="@+id/popUpAddItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Your Item"
            tools:ignore="MissingConstraints">
        </Button>
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/scrollViewItems">
            <!-- this LinearLayout is an exemple of the shape/structure of an item -->
            <LinearLayout
                android:clickable="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:id="@+id/protoItem">
                <TextView
                    android:clickable="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" Item1 "
                    android:id="@+id/protoName">
                </TextView>
                <TextView
                    android:clickable="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" Qt1 "
                    android:id="@+id/protoQuantity">
                </TextView>
                <TextView
                    android:clickable="true"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" Price1 "
                    android:id="@+id/protoPrice">
                </TextView>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>

    

</androidx.constraintlayout.widget.ConstraintLayout>

XML of the custom pop-up: "dialog_popup.xml"

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/window"
        tools:ignore="MissingConstraints">
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/itemName"
            android:hint="Enter the name of the item">
        </EditText>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/itemQuantity"
            android:hint="Enter the quantity of the item">
        </EditText>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/itemPrice"
            android:hint="Enter the price the item">
        </EditText>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Valider"
            android:id="@+id/validationButton">
        </Button>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Class to create a custom pop-up: "CreateCustomPopUp.java

package com.example.myapplication;

import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class CreateCustomPopUp extends Dialog {
    private LinearLayout page;
    private EditText name, quantity, price;
    private Button validation;
    private String varName="";
    private int varQt= 0;
    private float varPrice =0;
    public CreateCustomPopUp(Activity activity)
    {
        super(activity, androidx.appcompat.R.style.Theme_AppCompat_Dialog);
        setContentView(R.layout.dialog_popup);
        this.page = findViewById(R.id.window);
        this.name = findViewById(R.id.itemName);
        this.price = findViewById(R.id.itemPrice);
        this.quantity = findViewById(R.id.itemQuantity);
        this.validation = findViewById(R.id.validationButton);
        validation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                varName=name.getText().toString();
                varQt=Integer.valueOf(quantity.getText().toString());
                varPrice=Float.valueOf(price.getText().toString());
                dismiss();
            }
        });

    }
    public void build()
    {
        show();
    }
    public int getQt(){
        return varQt;
    }
    public String getName(){
        return varName;
    }
    public float getPrice(){
        return varPrice;
    }
}

Main activity Java : "MainActivity.java"

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;


public class MainActivity extends AppCompatActivity {
    public MainActivity activity;
    public String name ="";
    public int qt =0;
    public float price = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.activity=this;
        Button addItem = (Button) findViewById(R.id.popUpAddItem);
        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CreateCustomPopUp popUp = new CreateCustomPopUp(activity);
                popUp.build();
                popUp.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        name = popUp.getName();
                        qt = popUp.getQt();
                        price = popUp.getPrice();
                        //Put/call here a function/class or whatever works that add this created item in the scrollview
                    }
                });
            }
        });
        LinearLayout prototypeItem = (LinearLayout) findViewById(R.id.protoItem);
        prototypeItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Another popup that I'm borred to create, but I think you see the idea...
            }
        });
        // and here is my issue : I cant reproduce this "set on click listener" for each item... because they dont already exist and I dont know how many I'll have !
    }
}

Hope it’s clear and you can help me ^^

bye

Solution

Use a <RecyclerView> instead. RecyclerView is the best choice when you have multiple items of same type and you have to dynamically modify them. Follow these links to learn about recycler view and click listener in recycler view RecyclerView example. Recycler View Click Listener. I will briefly discuss how to do this.

  1. Create a item layout file. This is basically how each item of your recycler view looks. In your case this will be LinearLayout of protoitem declared in separate xml file.
  2. Create a data model file that defines that represents your single entity. eg. Create a class Item with fields name, quantity, price and appropriate methods.
  3. Add only recyler view in your activity_main.xml
  4. Create an adapter that loads your data into recycler view and link your adapter to recycler view.
  5. Create a list of your custom Item class List<Item> myList = new ArrayList<>();
  6. Now whenever you add new Item via dialog just add your item in myList and update your adapter by adapter.notifyDataSetChanged(); Adapter will automatically add that item in your recycler view.
  7. For click listener you need to create an interface in your adapter and implement that click listener in you main activity.

Answered By – Pawan Singh Harariya

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published