Skip to content Skip to sidebar Skip to footer

Recyclerview: How To Add Onclick() And Keep Onlongclick() Working?

I have an onClickListener set on a CheckBox for a RecyclerView that holds a list of CardViews. The listener is set up in my ItemHolder that extends ViewHolder. An initial click o

Solution 1:

How come you are not using OnCheckedChangeListener for checkbox?

CheckBoxchkBox= ( CheckBox ) findViewById( R.id.checkbox );
chkBox.setOnCheckedChangeListener(newOnCheckedChangeListener()
{
    @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform logic
        }

    }
});

Solution 2:

It seems you are trying to solve the wrong problem here. You should not set click & long click listeners on card view itself.

  • You can have click listener OR checkedChangeListener on Checkbox
  • click & long click listeners can be on rest of the view_container

Here if you want to check/uncheck the checkbox also on click of view_container, you can easily do it in view_container's onClick listener.

Edit: I have updated your layout file, notice now you have on FrameLayout as parent of RelativeLayout(view_container) & Checkbox.

As Checkbox is added after RelativeLayout it will be visible on top of view_container. Hope it will work for you.

Now you can set click listeners as I explained above.

Updated layout file

<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardViewxmlns:card_view="http://schemas.android.com/apk/res-auto"xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/singlecard_view1"android:layout_width="match_parent"android:layout_height="wrap_content"android:foreground="?android:attr/selectableItemBackground"
    ><FrameLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><RelativeLayoutandroid:id="@+id/view_container"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/statelist_cardview_background"  ><TextViewandroid:id="@+id/cardType1"android:layout_width="wrap_content"android:layout_height="30dp"android:layout_marginLeft="30dp"android:layout_marginStart="30dp"android:layout_alignParentTop="true"android:paddingStart="3dp"android:paddingLeft="3dp"android:paddingEnd="6dp"android:paddingRight="6dp"android:layout_marginTop="4dp"android:gravity="center"android:textColor="#ffffff"android:textStyle="bold|italic"style="@style/Base.TextAppearance.AppCompat.Subhead"  /><TextViewandroid:id="@+id/cardBlankText1"android:layout_width="wrap_content"android:layout_height="30dp"android:layout_alignParentTop="true"android:layout_toRightOf="@+id/cardType1"android:layout_toEndOf="@+id/cardType1"android:layout_toLeftOf="@+id/cardBlankTextNumstotal"android:layout_toStartOf="@+id/cardBlankTextNumstotal"android:layout_marginTop="4dp"android:gravity="center_vertical|end"android:text="#"android:textColor="@color/colorFlLabelFinal"android:textStyle="bold"android:maxLines="1"style="@style/Base.TextAppearance.AppCompat.Subhead"  /><TextViewandroid:id="@+id/cardBlankTextNumstotal"android:layout_width="wrap_content"android:layout_height="30dp"android:layout_alignParentTop="true"android:layout_alignParentEnd="true"android:layout_alignParentRight="true"android:gravity="center"android:text="actual card #"android:layout_marginTop="4dp"android:layout_marginRight="4dp"android:layout_marginEnd="4dp"android:freezesText="true"android:textColor="@android:color/black"android:maxLines="1"style="@style/Base.TextAppearance.AppCompat.Subhead"  /><TextViewandroid:id="@+id/cardBlankText2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_marginTop="34dp"android:layout_marginLeft="6dp"android:layout_marginStart="6dp"android:text="todo"android:textColor="@android:color/black"android:textStyle="bold"android:background="@drawable/todo_underline"android:maxLines="1"style="@style/Base.TextAppearance.AppCompat.Headline"  />

        ...
    </RelativeLayout><CheckBoxandroid:id="@+id/chkSelected"android:layout_width="wrap_content"android:layout_height="30dp"android:layout_alignParentTop="true"android:layout_alignParentStart="true"android:layout_alignParentLeft="true"android:layout_marginLeft="4dp"android:layout_marginStart="4dp"android:layout_marginTop="4dp"android:gravity="center"  /></FrameLayout></android.support.v7.widget.CardView>

Solution 3:

try this

publicclassMyRecylerAdapterextendsRecyclerView.Adapter<MyRecylerAdapter.ItemHolder> {

...

    publicMyRecylerAdapter(Context context, ArrayList<ListItem> listItems,
                            ArrayList<ListItem> selectedList) {
        this.mContext = context;
        this.mListItems = listItems;
        this.selectedItemsList = selectedList;
    }

    privateintselectedPos= -1;

    publicclassItemHolderextendsRecyclerView.ViewHolder {

        private CardView cardView;
        private CheckBox chkSelected;

        privateItemHolder(final View itemView) {
            super(itemView);

            cardView = (CardView) itemView.findViewById(R.id.singlecard_view1);
            chkSelected = (CheckBox) itemView.findViewById(R.id.chkSelected);
        }

        voidbind(int position) {

            if (checkedListItems.contains(position)) {
                chkSelected.setChecked(true);
            } else {
                chkSelected.setChecked(false);
            }
        }
    }

    @Overridepublic ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        Viewview= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_contact_item, parent, false);
        finalItemHolderitemHolder=newItemHolder(view);

        return itemHolder;
    }

    publicvoidonBindViewHolder(final ItemHolder itemHolder, finalint position) {

        finalListItemlistItem= mListItems.get(position);

        itemHolder.bind(position);

        if (checkedListItems.contains(position)) {
            itemHolder.cardView.setActivated(true);
        } else {
            itemHolder.cardView.setActivated(false);
        }

        if (itemHolder.getAdapterPosition() == selectedPos) {
            itemHolder.cardView.setActivated(true);
        } else {
            itemHolder.cardView.setActivated(false);
        }

        itemHolder.itemView.setOnClickListener(newView.OnClickListener() {
            // Handles the row being clicked.@OverridepublicvoidonClick(View view) {

                if (recyclerItemClickListener != null) {
                     recyclerItemClickListener.onItemClick(itemHolder.itemView, listItem);
               }
           }
       });

       itemHolder.itemView.setOnLongClickListener(newView.OnLongClickListener() {
           @OverridepublicbooleanonLongClick(View view) {

               if (recyclerItemClickListener != null) {
                   recyclerItemClickListener.onItemLongClick(itemHolder.itemView, listItem);
               }

               intadapterPos2= itemHolder.getAdapterPosition();
               if (adapterPos2 != android.support.v7.widget.RecyclerView.NO_POSITION) {
                   intlastSelectedPosition= selectedPos;
                   selectedPos = adapterPos2;
                   notifyItemChanged(lastSelectedPosition);
                   notifyItemChanged(selectedPos);
               }
               returntrue;
           }
       });

       itemHolder.chkSelected.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {

               if (position == android.support.v7.widget.RecyclerView.NO_POSITION) return;
               if (recyclerItemClickListener != null) {
                   recyclerItemClickListener.onCheckBoxClick(v, position);
               }
               IntegeriPos= position;

               if (((CheckBox) v).isChecked()) {
                   checkedListItems.add(iPos);
               } else {
                   checkedListItems.remove(iPos);
               }
           }
       });
   }

   @OverridepublicintgetItemCount() {
      return mListItems.size();
   }
}

Solution 4:

If I understood your question correctly Please try this code and let me know if it doesn't work

Adapter Java Code

publicclassAdapterextendsRecyclerView.Adapter<Adapter.ItemHolder> {

    private ArrayList<DemoData> mDemoData;

    publicAdapter() {
        mDemoData = newArrayList<>();
        for (inti=0; i <= 100; i++) {
            mDemoData.add(newDemoData("Item " + i, false));
        }
    }

    @Overridepublic ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        returnnewItemHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recyler_card, parent, false));
    }

    @OverridepublicvoidonBindViewHolder(ItemHolder holder, int position) {

        //Check if the item is check and toggle the checkboxif (mDemoData.get(position).checked) {
            holder.mCheckBox.setChecked(true);
        } else {
            holder.mCheckBox.setChecked(false);
        }

        //Set text to the textview
        holder.mTextView.setText(mDemoData.get(position).item);

    }

    @OverridepublicintgetItemCount() {
        return mDemoData.size();
    }

    publicclassItemHolderextendsRecyclerView.ViewHolder {
        private TextView mTextView;
        private CheckBox mCheckBox;

        publicItemHolder(View itemView) {
            super(itemView);
            mTextView = (TextView) itemView.findViewById(R.id.textView);
            mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);

            //set OnClickListener 
            itemView.setOnClickListener(newView.OnClickListener() {
                @OverridepublicvoidonClick(View v) {
                    Toast.makeText(mCheckBox.getContext(), "Clicked", Toast.LENGTH_SHORT).show();
                }
            });

            //set OnLongClickListener
            itemView.setOnLongClickListener(newView.OnLongClickListener() {
                @OverridepublicbooleanonLongClick(View v) {
                    //if handled return true if not return false;
                    Toast.makeText(mCheckBox.getContext(), "Long Clicked", Toast.LENGTH_SHORT).show();
                    returnfalse;
                }
            });

            mCheckBox.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
                @OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    mDemoData.get(getAdapterPosition()).checked = isChecked;
                }
            });
        }
    }
}

ItemView XML Code

<?xml version="1.0" encoding="utf-8"?><android.support.v7.widget.CardViewxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="75dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="75dp"android:orientation="horizontal"><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content" /><CheckBoxandroid:id="@+id/checkbox"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout></android.support.v7.widget.CardView>

Activity Java Code

publicclassRecyclerDemoActivityextendsAppCompatActivity {

    private RecyclerView mRecyclerView;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_demo);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(newLinearLayoutManager(getApplicationContext()));
        mRecyclerView.setAdapter(newAdapter());
    }
}

Just use this demo and change your code accordingly.

Edit: This is the model class which is used.

publicclassDemoData{
    publicString item;
    publicboolean checked;
    publicDemoData(String item,boolean isChecked){
    this.item=item;
    this.checked=isChecked;
    }
    }

|REY|

Solution 5:

you should give you data(mListItems) add a isChecked Fileds!and you can do this

holder.checkebox.setchecked(false);
if(mListItems.get(position).ischekced){
 holder.checkebox.setchecked(true);
}
holder.checkebox..setOnCheckedChangeListener(newOnCheckedChangeListener(){
@OverridepublicvoidonCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
  mListItems.get(position).isChecked=isChecked;

}
});

Post a Comment for "Recyclerview: How To Add Onclick() And Keep Onlongclick() Working?"