Rushabh Oswal
Rushabh Oswal

Reputation: 25

Adding Items in RecycleView Dynamically using a button

I have a button(save contact) to save contacts ,the button when pressed get name and email from edit text and should dynamically add 1 list item in recycle view

The save button is in fragment

This is the name which i am extracting

company_name=(EditText)view.findViewById(R.id.edittext_companyname_createMeeting);

When i click on lead it should add in the existing recycleview

 leads.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

     newValueAdapter.newAddeddata(company_name.getText().toString());*/
            }
        });

The recycle view already have a arraylist,how do i add new value to the arraylist and again call oncreate

I tried to extract company name and send it to the adapter of that recycler view but it dint work

Adapter of RecyclerView

public class NewleadsAdapter extends RecyclerView.Adapter<NewleadsAdapter.MyViewHolder> {

    Context context;
    LayoutInflater inflater;
    int positionbundle;
    ArrayList<NewleadsPOJO> datalist;
    public NewleadsAdapter(Context context, ArrayList<NewleadsPOJO> datalist,int positionbundle){

        this.context=context;
        this.datalist=datalist;
        this.positionbundle=positionbundle;

    }
   /* public NewleadsAdapter(){}*/

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=LayoutInflater.from(context).inflate(R.layout.custom_new_leads,parent,false);
        MyViewHolder myViewHolder=new MyViewHolder(view);
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {


        holder.leads_company.setText(datalist.get(position).getLeads_company());
        holder.leads_date.setText(datalist.get(position).getLeads_date());
        holder.leads_time.setText(datalist.get(position).getLeads_time());
        if (positionbundle == 1){
          /*  holder.icon1.setVisibility(View.GONE);*/
            holder.icon1.setImageResource(R.drawable.taskcompletednewblue);
    }else{}

        Log.e("Create_meetingdate_ArrayList:", datalist.get(0).getLeads_company());   /* Arrays.deepToString(data.toArray())*/
        System.out.println(datalist.get(0).getLeads_company());
    }

    @Override
    public int getItemCount() {
        return datalist.size();
    }


    public class MyViewHolder extends RecyclerView.ViewHolder{

       TextView leads_company,leads_date,leads_time;
        ImageView icon1;
        public MyViewHolder(View itemView) {
            super(itemView);

            leads_company=(TextView)itemView.findViewById(R.id.leads_company);
            leads_date=(TextView)itemView.findViewById(R.id.leads_date);
            leads_time=(TextView)itemView.findViewById(R.id.leads_time);
             icon1=(ImageView)itemView.findViewById(R.id.leads_info);
        }
    }


    /*public void newAddeddata(String company_name){
        NewleadsPOJO newValue=new NewleadsPOJO();
        newValue.setLeads_company(company_name);
        datalist.add(datalist.size(),newValue);

    }*/
}

Createmeetingfrag.java

public class CreateMeetingFrag extends Fragment {

TextView leads,cold,warm,hot,closed;
    EditText company_name,email,date,time;
    public CreateMeetingFrag() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_create_meeting, container, false);


        company_name=(EditText)view.findViewById(R.id.edittext_companyname_createMeeting);

        leads=(TextView)view.findViewById(R.id.meeting_leads);
        cold=(TextView)view.findViewById(R.id.meeting_cold);
        warm=(TextView)view.findViewById(R.id.meeting_warm);
        hot=(TextView)view.findViewById(R.id.meeting_hot);
        closed=(TextView)view.findViewById(R.id.meeting_closed);

        leads.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //getSavedValues();
               /* NewleadsAdapter newValueAdapter=new NewleadsAdapter();
                newValueAdapter.newAddeddata(company_name.getText().toString());*/

                NewleadsAdapter newValue=new NewleadsAdapter();

                newValue.newAddeddata(company_name.getText().toString());


                 setDefaultValues();
                leads.setBackgroundColor(getResources().getColor(R.color.blue));
                Toast.makeText(getActivity(),"leads clicked and saved",Toast.LENGTH_SHORT).show();
                leads.setTextColor(getResources().getColor(R.color.white));
            }
        });



        cold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDefaultValues();
                cold.setBackgroundColor(getResources().getColor(R.color.blue));
                Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
                cold.setTextColor(getResources().getColor(R.color.white));
            }
        });


        warm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDefaultValues();
                warm.setBackgroundColor(getResources().getColor(R.color.blue));
                Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
                warm.setTextColor(getResources().getColor(R.color.white));
            }
        });


        hot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDefaultValues();
                hot.setBackgroundColor(getResources().getColor(R.color.blue));
                Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
                hot.setTextColor(getResources().getColor(R.color.white));
            }
        });


        closed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDefaultValues();
                closed.setBackgroundColor(getResources().getColor(R.color.blue));
                Toast.makeText(getActivity(),"leads clicked",Toast.LENGTH_SHORT).show();
                closed.setTextColor(getResources().getColor(R.color.white));
            }
        });




        return view;

    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void setDefaultValues(){

        leads.setBackgroundColor(getResources().getColor(R.color.white));
        cold.setBackgroundColor(getResources().getColor(R.color.white));
        warm.setBackgroundColor(getResources().getColor(R.color.white));
        hot.setBackgroundColor(getResources().getColor(R.color.white));
        closed.setBackgroundColor(getResources().getColor(R.color.white));
        closed.setTextColor(getResources().getColor(R.color.black_semi_transparent));
        hot.setTextColor(getResources().getColor(R.color.black_semi_transparent));
        warm.setTextColor(getResources().getColor(R.color.black_semi_transparent));
        cold.setTextColor(getResources().getColor(R.color.black_semi_transparent));
        leads.setTextColor(getResources().getColor(R.color.black_semi_transparent));
        leads.setBackground(getResources().getDrawable(R.drawable.bordder_button));
        closed.setBackground(getResources().getDrawable(R.drawable.bordder_button));
        hot.setBackground(getResources().getDrawable(R.drawable.bordder_button));
        warm.setBackground(getResources().getDrawable(R.drawable.bordder_button));
        cold.setBackground(getResources().getDrawable(R.drawable.bordder_button));
    }




}

Upvotes: 1

Views: 28720

Answers (4)

Prince Patel
Prince Patel

Reputation: 499

How to add items and delete items in recycler view using floating button in java(android).

Add this dependency.

implementation 'com.google.android.material:material:1.4.0-alpha02'
implementation 'com.google.code.gson:gson:2.8.6'

MainActivity.java

fab = (FloatingActionButton) view.findViewById(R.id.fab_id);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LayoutInflater li = LayoutInflater.from(getContext());
            View v = li.inflate(R.layout.layout_dialog, null);

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());

            alertDialog.setTitle("Add Data");
            EditText title = v.findViewById(R.id.edittext_title);
            EditText description = v.findViewById(R.id.editview_description);
            alertDialog.setView(v);

            alertDialog.setPositiveButton("Add",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,int which) {

                            Gson gson = new Gson();
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("title", title.getText().toString());
                                jsonObject.put("description", description.getText().toString());
                                item item = gson.fromJson(String.valueOf(jsonObject), item.class);
                                items.add(item);
                                Adapter.notifyDataSetChanged();

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            alertDialog.setNegativeButton("cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            alertDialog.show();
        }
    });

layout_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="300dp"
android:orientation="vertical"
android:padding="60dp">

<EditText
    android:id="@+id/edittext_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/enter_title"
    app:layout_constraintBottom_toTopOf="@+id/editview_description"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:ignore="MissingConstraints"
    android:inputType="text"
    android:autofillHints="" />

<EditText
    android:id="@+id/editview_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp"
    android:hint="@string/enter_description"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/edittext_title"
    tools:ignore="MissingConstraints"
    android:autofillHints=""
    android:inputType="text" />

Adapter.java

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

List<item> mdata;

public Adapter(List<item> mdata) {
    this.mdata = mdata;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item, parent,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.tilte.setText(mdata.get(position).getTitle());
    holder.Description.setText(mdata.get(position).getDescription());

    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mdata.remove(position);
            notifyDataSetChanged();
        }
    });
}

@Override
public int getItemCount() {
    return mdata.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder{
    TextView tilte,Description;
    ImageView imageView;

public ViewHolder(@NonNull View itemView) {
    super(itemView);
    tilte=itemView.findViewById(R.id.title);
    Description=itemView.findViewById(R.id.description);
    imageView = itemView.findViewById(R.id.remove_image);
}

}
}

layout_item.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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="55dp">

<ImageView
    android:id="@+id/imageView"
    android:layout_width="12dp"
    android:layout_height="12dp"
    android:layout_marginStart="4dp"
    android:layout_marginTop="4dp"
    android:contentDescription="@string/mark"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/circle_img" />

<View
    android:id="@+id/view"
    android:layout_width="1dp"
    android:layout_height="0dp"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:background="#800080"
    app:layout_constraintBottom_toBottomOf="@+id/description"
    app:layout_constraintEnd_toEndOf="@id/imageView"
    app:layout_constraintStart_toStartOf="@id/imageView"
    app:layout_constraintTop_toBottomOf="@id/imageView" />

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="60dp"
    android:layout_marginTop="16dp"
    android:textStyle="bold"
    android:textSize="16sp"
    android:inputType="text"
    app:layout_constraintStart_toEndOf="@+id/imageView"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/description"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:lineSpacingExtra="1sp"
    android:padding="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/imageView"
    app:layout_constraintTop_toBottomOf="@+id/title" />

<ImageView
    android:id="@+id/remove_image"
    android:layout_width="20dp"
    android:layout_height="24dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="24dp"
    android:contentDescription="@string/remove_item"
    app:layout_constraintEnd_toStartOf="@+id/title"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@android:drawable/ic_menu_close_clear_cancel" />
</androidx.constraintlayout.widget.ConstraintLayout>

item.java

public class item {
private String title;
private String description;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public item(String title, String description) {
    this.title = title;
    this.description = description;
}
}

Upvotes: 1

Ketan Ramani
Ketan Ramani

Reputation: 5753

layout

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvContactNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:nestedScrollingEnabled="false"
    android:overScrollMode="never"
    tools:itemCount="2"
    tools:listitem="@layout/row_add_contact_number" />

java

private ArrayList<ContactNumberModel> arrayList;
private ContactNumberAdapter adapter;

onCreate

arrayList = new ArrayList<>();
arrayList.add(new ContactNumberModel());
adapter = new ContactNumberAdapter(context);

binding.rvContactNumber.setLayoutManager(new LinearLayoutManager(context));
binding.rvContactNumber.setHasFixedSize(true);
binding.rvContactNumber.setAdapter(adapter);

ContactNumberModel.java

public class ContactNumberModel {
    private String contactNo;

    public String getContactNo() {
        return contactNo;
    }

    public void setContactNo(String contactNo) {
        this.contactNo = contactNo;
    }
}

ContactNumberAdapter.java

public class ContactNumberAdapter extends RecyclerView.Adapter<ContactNumberAdapter.ViewHolder> {

    private Context context;
    private ArrayList<ContactNumberModel> arrayList;

    public ContactNumberAdapter(Context context) {
        this.context = context;
        this.arrayList = new ArrayList<>();
        this.arrayList.add(new ContactNumberModel());
    }

    @NonNull
    @Override
    public ContactNumberAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RowAddContactNumberBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.row_add_contact_number, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull final ContactNumberAdapter.ViewHolder holder, int position) {
        ContactNumberModel model = arrayList.get(position);
        //holder.bind(model);
        holder.binding.etContactNumber.setText("");

        holder.binding.etContactNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                arrayList.get(holder.getAdapterPosition()).setContactNo(editable.toString());
            }
        });

        if (arrayList.size() - 1 == holder.getAdapterPosition()) {
            holder.binding.tvAddMore.setVisibility(View.VISIBLE);
            holder.binding.ivRemove.setVisibility(View.GONE);
        } else {
            holder.binding.tvAddMore.setVisibility(View.GONE);
            holder.binding.ivRemove.setVisibility(View.VISIBLE);
        }

        holder.binding.ivRemove.setOnClickListener(null);
        holder.binding.tvAddMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNewRow();
            }
        });
    }

    public void addNewRow() {
        this.arrayList.add(new ContactNumberModel());
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        RowAddContactNumberBinding binding;

        public ViewHolder(RowAddContactNumberBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        public void bind(ContactNumberModel model) {
            binding.setContact(model);
            binding.executePendingBindings();
        }
    }
}

row_add_contact_number.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="contact"
            type="com.appname.model.ContactNumberModel" />
    </data>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/_10sdp"
        android:orientation="vertical">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/_15sdp"
            android:layout_marginRight="@dimen/_15sdp"
            android:gravity="center"
            android:orientation="horizontal">

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:theme="@style/TextInputLayoutHint">

                <androidx.appcompat.widget.AppCompatEditText
                    android:id="@+id/etContactNumber"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:clickable="false"
                    android:focusableInTouchMode="true"
                    android:hint="Enter Contact Number"
                    android:inputType="number"
                    android:maxLines="1" />

            </com.google.android.material.textfield.TextInputLayout>

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/tvAddMore"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/_3sdp"
                android:layout_marginLeft="@dimen/_3sdp"
                android:fontFamily="@font/font_barlow"
                android:gravity="center"
                android:text="@string/add_more"
                android:textColor="@color/colorOrange"
                android:textSize="@dimen/_12ssp"
                android:textStyle="bold" />

            <androidx.appcompat.widget.AppCompatImageView
                android:id="@+id/ivRemove"
                android:layout_width="@dimen/_15sdp"
                android:layout_height="@dimen/_15sdp"
                android:layout_marginLeft="@dimen/_5sdp"
                android:adjustViewBounds="true"
                android:src="@drawable/ic_logo"
                android:visibility="gone" />

        </androidx.appcompat.widget.LinearLayoutCompat>

        <View style="@style/Divider" />

    </androidx.appcompat.widget.LinearLayoutCompat>

</layout>

Upvotes: 0

Pratik Popat
Pratik Popat

Reputation: 2999

Add this method to your adapter and call on button click.

public void newAddeddata(String company_name){
        NewleadsPOJO newValue=new NewleadsPOJO();
        newValue.setLeads_company(company_name);
        datalist.add(newValue);
        notifyDataSetChanged();
    }

Add following method to NewLeadFrag

public NewleadsAdapter getAdapter(){
   return adapter;
}

now in Createmeetingfrag

leads.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewLeadFrag fragment = getFragmentManager().findFragmentByTag("NewLeadFrag_TAG"); //set tag of fragment when you add with fragment manager. and if you are using support library use getSupportFragmentManager()
               if(fragment!= null){
                    fragment.getAdapter().newAddeddata(company_name.getText().toString());
                }

            }
        });

Upvotes: 6

Abbas
Abbas

Reputation: 3331

You don't need to go through the entire life cycle of your Activity or Fragment just because you've made changes to the list. Instead try adding the item in the list you currently have associated with the Adapter. And then call adapter.notifyDataSetChange(). This should automatically add the new Item to the RecyclerView.

Upvotes: 1

Related Questions