使用按钮动态添加RecycleView中的项目

时间:2017-06-23 10:57:56

标签: android android-recyclerview

我有一个保存联系人的按钮(保存联系人),按下时按钮从编辑文本中获取姓名和电子邮件,并应在循环视图中动态添加1个列表项

保存按钮位于片段

这是我正在提取的名称

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

当我点击引导时,它应该添加现有的recycleview

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

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

循环视图已经有一个arraylist,我如何向arraylist添加新值并再次调用oncreate

我尝试提取公司名称并将其发送到该回收站视图的适配器,但它正在工作

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));
    }




}

4 个答案:

答案 0 :(得分:5)

将此方法添加到适配器并调用按钮单击。

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

将以下方法添加到NewLeadFrag

public NewleadsAdapter getAdapter(){
   return adapter;
}

现在在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());
                }

            }
        });

答案 1 :(得分:1)

如何使用java(android)中的浮动按钮在回收站视图中添加和删除项目。

添加此依赖项。

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" />

适配器.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;
}
}

答案 2 :(得分:0)

您不需要经历ActivityFragment的整个生命周期,只是因为您已对列表进行了更改。而是尝试在当前与Adapter关联的列表中添加项目。然后拨打adapter.notifyDataSetChange()。这应该会自动将新项目添加到RecyclerView

答案 3 :(得分:0)

布局

<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>