Search code examples
androidviewonitemclicklisteneronitemclick

onItemClick is returning different values


I have this ViewHolder in my adapter.

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        ImageView optionImage;
        ImageView optionAddFavorites;
        BMLTextView optionText;
        RelativeLayout lay_icon;

        ViewHolder(View itemView) {
            super(itemView);
            optionImage = (ImageView) itemView.findViewById(R.id.img_option);
            optionAddFavorites = (ImageView) itemView.findViewById(R.id.iv_add_favorites);
            optionText = (BMLTextView) itemView.findViewById(R.id.txt_option_description);
            lay_icon = (RelativeLayout) itemView.findViewById(R.id.lay_icon);

            itemView.setOnClickListener(this);

            this.setIsRecyclable(false);
        }

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

Later, in my Activity I've implement:

public class OperateOptionSectionItemHelperImpl
        implements OperateOptionRVAdapter.ItemClickListener, OperateOptionSectionItemHelper {

I've done an override of the method onItemClick, like the next:

@Override
    public void onItemClick(View view, int position) {
    if (isEditingFavorites) {

        switch (view.getId()) {

            case R.id.iv_add_favorites:
                Log.e("onItemClick", "Add to favorites iv_add_favorites: " + R.id.iv_add_favorites + " parent: " + view.getId());

                break;
            case R.id.img_option:
                Log.e("onItemClick", "Add to favorites img_option: " + R.id.img_option + " parent: " + view.getId());

                break;

            default:
                Log.e("onItemClick", "Default");

        }

    } else {
        Log.e("onItemClick", "Rest of the view");

        }
    }
}

I'm not getting the id of the view clicked... What I'm doing wrong?


Solution

  • that's because you set the ClickListener to the itemView. In face you should set ClickListener to optionImage and optionAddFavorites change

    itemView.setOnClickListener(this);
    

    to

    optionImage.setOnClickListener(this);
    optionAddFavorites.setOnClickListener(this);