Gyan S Awasthi
Gyan S Awasthi

Reputation: 247

how to implement checkbox in recyclerView?

I have an adapter for recyclerview. Where i pass array list from my activity like where data is ArrayList having some data.

 AlternativeAdapter alternativeAdapter= new AlternativeAdapter(AlternativeActivity.this, data);

    recyclerView.setAdapter(alternativeAdapter);

In the AlternativeAdapter class i have a textview and check box. I am able to display all text item with check boxes.

In the AlternativeAdapter class

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

 ArrayList<String> currencyListArray;
    Context context;
    View view1;
    ViewHolder viewHolder1;
    TextView textView;
    private int selectedPosition = -1;// no selection by default
    public AlternativeCurrencyAdapter(Context context1, ArrayList<String> currencyListArray){

        this.currencyListArray = currencyListArray;
        context = context1;
    }    
    public  class ViewHolder extends RecyclerView.ViewHolder{

        public TextView username;
        public CheckBox chkSelected;
        public ViewHolder(View v){
            super(v);
            username = (TextView)v.findViewById(R.id.username);
            chkSelected = (CheckBox) v.findViewById(R.id.chkSelected);
            itemView.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    // get position
                    int pos = getAdapterPosition();

                    // check if item still exists
                    if(pos != RecyclerView.NO_POSITION){
                        String clickedDataItem = currencyListArray.get(pos);
                        Toast.makeText(v.getContext(), "You clicked " + clickedDataItem, Toast.LENGTH_SHORT).show();

                    }
                }
            });

        }
    }

    @Override
    public AlternativeCurrencyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){

        view1 = LayoutInflater.from(context).inflate(R.layout.alternative_currency_adapter_list,parent,false);

        viewHolder1 = new ViewHolder(view1);

        return viewHolder1;
    }

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

        holder.username.setText(currencyListArray.get(position));
    }
    @Override
    public int getItemCount(){
        return currencyListArray.size();
    }
}

By this way the item of array list is displaying but my need is at item should display at left corner and checkbox of each item should display at right corner . when some one clicks on check box toast message should come like you selected XYZ item. And only single selection is required not multi selection.

when i use

 holder.chkSelected.setChecked(currencyListArray.get(position).isSelected());

I shows compile time error. Can not resolve isSelected()

Please guide me.

Upvotes: 5

Views: 7090

Answers (2)

Quick learner
Quick learner

Reputation: 11477

Working example

    class ApplicationsAdapter(val userList: ArrayList<DataX>, var callBack: AdapterCallback) :
        RecyclerView.Adapter<ApplicationsAdapter.ViewHolder>() {
        interface AdapterCallback {
            fun onAppLockedUnlocked(position: Int, status: Boolean)
        }
    
        //this method is returning the view for each item in the list
        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): ViewHolder {
            val v =
                LayoutInflater.from(parent.context).inflate(R.layout.item_view_app_list, parent, false)
            return ViewHolder(v)
        }
    
        //this method is binding the data on the list
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            holder.bindItems(userList[position], callBack)
        }
    
        //this method is giving the size of the list
        override fun getItemCount(): Int {
            return userList.size
        }
    
        //the class is hodling the list view
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    
            fun bindItems(
                dataX: DataX,
                callBack: AdapterCallback
            ) {
                val tvAppName = itemView.findViewById(R.id.tvAppName) as TextView
                val checkboxLockUnlock = itemView.findViewById(R.id.checkboxLockUnlock) as CheckBox
                tvAppName.text = dataX.appName

                // set listener null here
                checkboxLockUnlock.setOnCheckedChangeListener(null)
                if (dataX.isLocked) {
                    checkboxLockUnlock.isChecked = true
                } else {
                    checkboxLockUnlock.isChecked = false
                }
               // initialize listener after checkbox state changed 

checkboxLockUnlock.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
                    if (isChecked) {
                        callBack.onAppLockedUnlocked(adapterPosition, true)
                    } else {
                        callBack.onAppLockedUnlocked(adapterPosition, false)
                    }
                }
                )
            }
        }
    }

Upvotes: 0

Ankit Patidar
Ankit Patidar

Reputation: 2781

First thing, your currencyListArray is arraylist of string so it doesnot return for "isSelected()" sorry!

and now come to your requirement, you need to show message when any of checkbox is selected.

So code like this:

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

    holder.username.setText(currencyListArray.get(position));
    holder.chkSelected.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            //do your toast programming here.
        }
    });
}

now come to your second requirement, for selecting only one item at a time: here is code for that::

 chkSelected.setChecked(position== selectedPosition);

        chkSelected.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                {
                    selectedPosition =  position;
                }
                else{
                     selectedPosition = -1;
                }
                notifyDataSetChanged();
            }
        });

Upvotes: 6

Related Questions