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

新手上路,请多包涵

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

保存按钮在片段中

这是我正在提取的名称

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

当我点击铅时,它应该添加到现有的回收视图中

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

    }*/
}

创建meetingfrag.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));
    }

}

原文由 Rushabh Oswal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 419
2 个回答

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

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

            }
        });

原文由 Pratik Popat 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

添加此依赖项。

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

主活动.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();
        }
    });

布局对话框.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>

项目.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;
}
}

原文由 Prince Patel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题