Callback method in list Adapter doesn't work

前端 未结 2 1033
南笙
南笙 2021-01-29 08:52

I used a callback methods I was guided to use in a previous question. It doesn\'t seem to work. The onClick() method is not called. callback methods seem to be a very broad conc

相关标签:
2条回答
  • 2021-01-29 09:08

    You don't need to pass view and position, just pass the object you want.

    Change your interface parameter

     public interface ItemClickListener {
         void onItemClick(Country country);
     }
    

    and you can pass the object you need

    public void onClick(View view) {
    
         final Country currentCountry = countriesList.get(getAdapterPosition());
    
         mClickListener.onItemClick(currentCountry);
    }
    

    In your Activity, get your Country

     @Override
     public void onItemClick(Country country) {
    
          //  get country and do anything you want
     }
    

    Hope this helps

    0 讨论(0)
  • 2021-01-29 09:21

    That's because you are missing @Override annotation inside your RowViewHolder's onClick method.

    It should look like below.

    class RowViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
            TextView viewName;
            ImageView viewFlag;
            LinearLayout countryEntry;
    
            RowViewHolder(View view) {
    
                super(view);
                viewName = view.findViewById(R.id.name);
                viewFlag = view.findViewById(R.id.flag);
                countryEntry = view.findViewById(R.id.rowId);
                view.setOnClickListener(this);
            }
    
            @Override
            public void onClick(View view) {
                if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
                ListActivity.position = getAdapterPosition();
                final Country currentCountry = countriesList.get(getAdapterPosition());
                listActivity.setCurrentCountry(currentCountry);
    
            }
        }
    
    
    0 讨论(0)
提交回复
热议问题