需要将选中的(多个)RecyclerView项目行用复选框放到另一个有RecyclerView的Activity中。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了需要将选中的(多个)RecyclerView项目行用复选框放到另一个有RecyclerView的Activity中。相关的知识,希望对你有一定的参考价值。

我需要将选中的(多个)RecyclerView项目行使用复选框放在另一个同样使用RecyclerView的活动中。我已经尝试了很多方法来解决这个问题,但我无法找到任何解决方案。所以请大家帮我解决这个问题,找到一个合适的解决方案。

谢谢!这是我的适配器。

这是我的适配器。 (我需要使用复选框选择多个RecyclerView项目行,并放入另一个。)

(这就是布局示例 )


import android.content.Context;
import android.content.Intent;
import android.os.Build;

import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import static java.text.DateFormat.DEFAULT;


public class sacAdapter extends RecyclerView.Adapter<sacAdapter.MyViewHolder>
        implements Filterable {
    private Context context;
    private List<SAClist> SaCList;
    private List<SAClist> SACListFiltered;

    Double a;
    int b;
    int c;
    Double d;
    LayoutInflater inflater;
    Double e;
    ViewGroup viewGroup;
    Double value5;

    SAC myActivity;


    private SACAdapterListener listener;
    private DecimalFormat df2 = new DecimalFormat("#############.##");
    private DecimalFormat df = new DecimalFormat("0.#");
    private int number = 0;
    private int number1 = 0;


    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView ProName, Rate, Qty, Total;
        public ImageView thumbnail;
        public Button Qty1, Qty2;
        CheckBox check;
        TextView cartICON;


//        public ImageView thumbnail;

        public MyViewHolder(View view) {
            super(view);


            ProName = view.findViewById(R.id.ProName);
            Rate = view.findViewById(R.id.Rate);
            Qty = view.findViewById(R.id.Qty);
            check = view.findViewById(R.id.check);
            Total = view.findViewById(R.id.Total);
            Qty1 = view.findViewById(R.id.Qty1);
            Qty2 = view.findViewById(R.id.Qty2);
            check = view.findViewById(R.id.check);


            thumbnail = view.findViewById(R.id.thumbnail);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // send selected contact in callback
                    listener.onSACSelected(SACListFiltered.get(getAdapterPosition()));
                }
            });
        }
    }


    public sacAdapter(Context context, List<SAClist> sacList, SACAdapterListener listener) {
        this.context = context;
        this.listener = listener;
        this.SaCList = sacList;
        this.SACListFiltered = sacList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
        View itemView = LayoutInflater.from(parent1.getContext())
                .inflate(R.layout.sac_item_row, parent1, false);

        return new MyViewHolder(itemView);

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {


        final SAClist saclist = SACListFiltered.get(position);
        holder.ProName.setText(saclist.getPName());
        holder.Rate.setText("Rate : " + saclist.getPRate());


        String Ra = saclist.PRate;
        double value1 = Ra.isEmpty() ? 0.0 : Double.parseDouble(Ra);
        String TOT1 = holder.Qty.getText().toString().trim();
        final double value3 = TOT1.isEmpty() ? 0.0 : Double.parseDouble(TOT1);

        a = value1 * value3;
        String stringValue35 = Double.toString(Double.parseDouble(df2.format(a)));
        holder.Total.setText("TOTAL : " + stringValue35);


        byte[] decoder = Base64.decode(saclist.getPImage(), DEFAULT);


        Glide.with(context)
                .load(decoder)
                .apply(RequestOptions.noTransformation())
                .into(holder.thumbnail);


        holder.Qty1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                number = Integer.parseInt(holder.Qty.getText().toString());
                number++;

                holder.Qty.setText("" + number);

                ////////////////////////////
                String Ra = saclist.PRate;
                double value1 = Ra.isEmpty() ? 0.0 : Double.parseDouble(Ra);
                String TOT5 = holder.Qty.getText().toString().trim();
                value5 = TOT5.isEmpty() ? 0.0 : Double.parseDouble(TOT5);

                a = value1 * value5;
                String stringValue35 = Double.toString(Double.parseDouble(df2.format(a)));
                holder.Total.setText("TOTAL : " + stringValue35);

                if (number <= 0) {
                    holder.check.setChecked(false);
                } else {
                    holder.check.setChecked(true);
                }


                number1++;
                SAC.update_counter(""+number1);
            }
        });
        holder.Qty2.setOnClickListener(new View.OnClickListener()  {
            @Override
            public void onClick(View view) {

                number = Integer.parseInt(holder.Qty.getText().toString());
                if (number <= 0) {
                    number = 0;
                } else {

                    number--;


                    holder.Qty.setText("" + number);
                }

                /////////////////////////////////
                String Ra = saclist.PRate;
                double value1 = Ra.isEmpty() ? 0.0 : Double.parseDouble(Ra);
                String TOT = holder.Qty.getText().toString().trim();
                double value2 = TOT.isEmpty() ? 0.0 : Double.parseDouble(TOT);

                a = value1 * value2;
                String stringValue35 = Double.toString(Double.parseDouble(df2.format(a)));
                holder.Total.setText("TOTAL : " + stringValue35);

                if (number <= 0) {
                    holder.check.setChecked(false);
                } else {
                    holder.check.setChecked(true);
                }

                number1--;
                    SAC.update_counter("" + number1);
            }


        });
//        holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (holder.check.isChecked()) {
//                    number1++;
//                    SAC.update_counter("" + number1);
//                }
//                if (!holder.check.isChecked()) {
//                    number1--;
//                    SAC.update_counter("" + number1);
//                }
//            }
//        });



    }



    @Override
    public int getItemCount() {

        return SACListFiltered.size();
    }

    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                String charString = charSequence.toString();
                if (charString.isEmpty()) {
                    SACListFiltered = SaCList;
                } else {
                    List<SAClist> filteredList = new ArrayList<>();
                    for (SAClist row : SaCList) {

                        // name match condition. this might differ depending on your requirement
                        // here we are looking for name or phone number match
                        if (row.getPName().toLowerCase().contains(charString.toLowerCase())) {
                            filteredList.add(row);
                        }
                    }

                    SACListFiltered = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = SACListFiltered;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                SACListFiltered = (ArrayList<SAClist>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    public interface SACAdapterListener {
        void onSACSelected(SAClist sac);
    }




}

我的活动

package com.i.menu;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class SAC extends AppCompatActivity implements sacAdapter.SACAdapterListener {
    private static final String TAG = SAC.class.getSimpleName();
    private RecyclerView recyclerView1;
    private List<SAClist> SaCList;
    private sacAdapter mAdapter;
    private SearchView searchView;
    ProgressBar progressBar1;
    TextView cartICON;
    Context context;

    String name, name1;

    private final String URL = "https://.....php/";

    public static TextView counter_value;


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

        counter_value = findViewById(R.id.cartICON);


        progressBar1 = findViewById(R.id.progress1);
        progressBar1.setVisibility(View.VISIBLE);
        Toolbar toolbar1 = findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar1);

        // toolbar fancy stuff
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("MENU");

        recyclerView1 = findViewById(R.id.recycler_view1);
        SaCList = new ArrayList<>();
        mAdapter = new sacAdapter(this, SaCList, this);

        // white background notification bar
        whiteNotificationBar(recyclerView1);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView1.setLayoutManager(mLayoutManager);
        recyclerView1.setItemAnimator(new DefaultItemAnimator());
        recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
        recyclerView1.setAdapter(mAdapter);

        fetchSAC();
    }

    private void fetchSAC() {


        JsonArrayRequest request = new JsonArrayRequest(URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
                            return;
                        }

                        List<SAClist> items = new Gson().fromJson(response.toString(), new TypeToken<List<SAClist>>() {
                        }.getType());

                        // adding contacts to contacts list
                        SaCList.clear();
                        SaCList.addAll(items);

                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();
                        progressBar1.setVisibility(View.GONE);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error in getting json
                Log.e(TAG, "Error: " + error.getMessage() +error.getCause());

                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        APP.getInstance().addToRequestQueue(request);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.action_search)
                .getActionView();
        assert searchManager != null;
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        // listening to search query text change
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // filter recycler view when query submitted
                mAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                // filter recycler view when text is changed
                mAdapter.getFilter().filter(query);
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // close search view on back button pressed
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
            return;
        }
        super.onBackPressed();

    }

    private void whiteNotificationBar(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int flags = view.getSystemUiVisibility();
            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            view.setSystemUiVisibility(flags);
            getWindow().setStatusBarColor(Color.WHITE);
        }
    }


    @Override
    public void onSACSelected(final SAClist sac) {



    }




    public static void update_counter(String value) {
        try {
            counter_value.setText(value);


        } catch (Exception ex) {
            Log.d("Exception", "Exception of type" + ex.getMessage());
        }
    }
}



import android.os.Parcel;
import android.os.Parcelable;

public class SAClist implements Parcelable {

    String PImage;
    String PName;
    String PRate;


    public SAClist() {
    }

    protected SAClist(Parcel in) {
        PImage = in.readString();
        PName = in.readString();
        PRate = in.readString();
    }

    public static final Creator<SAClist> CREATOR = new Creator<SAClist>() {
        @Override
        public SAClist createFromParcel(Parcel in) {
            return new SAClist(in);
        }

        @Override
        public SAClist[] newArray(int size) {
            return new SAClist[size];
        }
    };

    public String getPImage() {
            return PImage;
        }

        public String getPName() {
            return PName;
        }

        public String getPRate() {
            return PRate;
        }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(PImage);
        dest.writeString(PName);
        dest.writeString(PRate);
    }
}


新的RecyclerView

package com.i.menu;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class JUR extends AppCompatActivity implements jurAdapter.ItemClickListener {

    jurAdapter adapter;
    SAClist saClists;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jur);


        Bundle bundle = getIntent().getExtras();
        ArrayList<SAClist> sacList = bundle.getParcelableArrayList("selectedSACList");



        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.recycler_view2);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new jurAdapter(this, sacList);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);

        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

    }


    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();

    }
}

其适配器

package com.i.menu;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

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

    private ArrayList<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    jurAdapter(Context context, ArrayList<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.jur_item_row, parent, false);
        return new ViewHolder(view);
    }



    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);

        holder.ProName1.setText(animal);
    }

    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView ProName1, Rate1, Qty1, Total1;
        public ImageView thumbnail1;
        public Button ADD, MIN;


        ViewHolder(View itemView) {
            super(itemView);
             ProName1 = itemView.findViewById(R.id.ProName1);
//             Rate1 = itemView.findViewById(R.id.Rate1);
//             Qty1 = itemView.findViewById(R.id.Qty1);
//             Total1 = itemView.findViewById(R.id.Total1);
//             ADD = itemView.findViewById(R.id.ADD);
//             MIN = itemView.findViewById(R.id.MIN);


//            ImageView thumbnail1 = itemView.findViewById(R.id.thumbnail1);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

答案

我将试着解释如何做。

首先,把你的监听器改成这样。

void onSACSelected(SAClist sac, boolean isChecked);

在你的onClickListener中发送检查的信息到活动中,就像这样。

listener.onSACSelected(SACListFiltered.get(getAdapterPosition()), check.isChecked());

在你的活动中创建一个新的列表,像这样。

private ArrayList<SAClist> selectedSACList;

在你的活动中改变你的onSACSelected方法。

@Override
public void onSACSelected(final SAClist sac, boolean isChecked) {
    // You should check list first, if selected items are exist!
    if (isChecked) {
        selectedSACList.add(sac);    
    } else {
        selectedSACList.remove(sac);
    }
}

将你的列表传递给新的活动,就像下面这样。

Intent intent = new Intent(this, NewActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("selectedSACList", selectedSACList); // You should make your object Parcelable
intent.putExtras(bundle);
startActivity(intent);

在你的新活动中创建一个新的recyclerview,并用数组列表填充你的适配器。你可以得到这样的列表。

Bundle bundle = getIntent().getExtras();
ArrayList<SAClist> sacList = bundle.getParcelableArrayList("selectedSACList");

希望它能工作。希望能成功。

以上是关于需要将选中的(多个)RecyclerView项目行用复选框放到另一个有RecyclerView的Activity中。的主要内容,如果未能解决你的问题,请参考以下文章

如何从另一个项目更新recyclerview项目中的数据?

滚动后选中的复选框在recyclerview中变为未选中

滚动时,在recyclerView中取消选中复选框

notifyItemChanged(int position) 更新 RecyclerView 中的多个项目

在 RecyclerView 中使用多个视图类型时如何将项目添加到所需的 ViewHolder 位置?

单击recyclerview上的项目时的多个数据