RecyclerVIew onItemClickListener Not working

2020-05-06 10:10发布

问题:

I am working on RecyclerView and try to using on click listener for each item of recyclcerview using Interface

Here is my Activity class:

public class LegacyHomeActivity extends ActivityBaseDrawer {
    private List<LegacyVideo> legacyVideoList = null;
    private List<Video> videoList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private LegacyModeHomeAdapter adapter;

    @Override
    public void onNetworkStateChanged(boolean connected) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isLegacyMode = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_legacy_home);
        if (getSupportActionBar() != null) {
            setTitle(getString(R.string.footy_legacy_home));
        }
        ImageView legacy_live_score_imageView = (ImageView) findViewById(R.id.legacy_live_score_imageView);
        legacy_live_score_imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LegacyHomeActivity.this, LegacyLiveScoreActivity.class));
            }
        });
        ImageView legacy_highlight_imageView = (ImageView) findViewById(R.id.legacy_highlight_imageView);
        legacy_highlight_imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LegacyHomeActivity.this, LegacyHighlightsActivity.class));
            }
        });
        ImageView legacy_news_imageView = (ImageView) findViewById(R.id.legacy_news_imageView);
        legacy_news_imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LegacyHomeActivity.this, LegacyNewsActivity.class));
            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.legacy_mood_recyclerview);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        adapter = new LegacyModeHomeAdapter(getApplicationContext(), itemClickListener);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.setHasFixedSize(true);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.ThemeColor,
                R.color.ThemeColor, R.color.ThemeColor);
        swipeRefreshLayout
                .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

                    @Override
                    public void onRefresh() {
                        getLegacyVideoList();
                    }
                });

        circularProgressView = (CircularProgressView) findViewById(R.id.circularProgressView);
        showLoadingProgress();
        getLegacyVideoList();
    }

    LegacyVideoClickListener itemClickListener = new LegacyVideoClickListener() {
        @Override
        public void onItemClickListener(int position) {
            Video video = videoList.get(position);
            VideoPlayerUtil.initVideoPLayer(video, LegacyHomeActivity.this);
        }
    };

    private void getLegacyVideoList() {
        FootyLightAPI api = new FootyLightAPI(getApplicationContext(), mResponseListener);
        api.getLegacyHomeVideoList();
    }

    private final FootyLightAPI.ResponseListener mResponseListener = new FootyLightAPI.ResponseListener() {
        @Override
        public void getResponse(int apiId, final String response) {
            switch (apiId) {
                case R.integer.ApiLegacyVideoList:
                    Log.e("Legacy  ............", "Response:................" + response);
                    try {
                        final ObjectMapper mapper = new ObjectMapper();
                        legacyVideoList = mapper.readValue(response, new TypeReference<List<LegacyVideo>>() {
                        });
                        if (legacyVideoList != null && legacyVideoList.size() > 0) {
                            videoList.clear();
                            for (LegacyVideo video : legacyVideoList) {
                                Log.e("Legacy video", "" + video.getTitle());
                                Video videoItem = new Video();
                                if (video.getItemType().equalsIgnoreCase("video")) {
                                    videoItem.setTitle(video.getTitle());
                                    videoItem.setLink(video.getLink());
                                    videoItem.setThumb(video.getThumb());
                                    videoItem.setContentType(video.getContentType());
                                    videoItem.setContentUrl(video.getContentUrl());
                                    videoItem.setDmcaLabel(video.getDmcaLabel());
                                    videoItem.setDmcaContent(video.getDmcaContent());
                                    videoItem.setDmcaDisclaimer(video.getDmcaDisclaimer());
                                    videoItem.setDisplayType(video.getDisplayType());
                                    videoList.add(videoItem);
                                }

                            }
                        }
                        Log.e("VideoList", "........." + videoList.size());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showVideoAdapter();
                                hideLoadingProgress();

                            }
                        });


                    } catch (Exception e) {

                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void getError(int apiId, int errorCode) {
        }

        @Override
        public void getResponse(String trackingStr, int apiId, String response) {

        }

        @Override
        public void getError(String trackingStr, int apiId, int errorCode) {

        }
    };

    public void showVideoAdapter() {
        if (adapter != null) {
            adapter.setVideos(videoList);
        }
    }
}

And here is my Adapter Class

public class LegacyModeHomeAdapter extends RecyclerView.Adapter<LegacyModeHomeAdapter.ItemViewHolder> {
    private List<Video> videoList;
    private Context mContext;
    private LegacyVideoClickListener onVideosRVItemClickListener;

    private LayoutInflater getLayoutInflater() {
        return LayoutInflater.from(mContext);
    }

    public LegacyModeHomeAdapter(Context mContext, LegacyVideoClickListener onVideosRVItemClickListener) {
        this.mContext = mContext;
        this.onVideosRVItemClickListener = onVideosRVItemClickListener;
    }

    public void setVideos(List<Video> videosList) {
        this.videoList = videosList;
        notifyDataSetChanged();
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, final int position) {
        Video video = videoList.get(position);
        Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
        holder.categoryName.setText(video.getTitle());
        holder.title_image_btn.setText(video.getDisplayType());
        holder.VideosItemClickListener(position, onVideosRVItemClickListener);
    }

    @Override
    public int getItemCount() {
        if (videoList != null) {
            return videoList.size();
        }
        return 0;
    }

    public class ItemViewHolder extends RecyclerView.ViewHolder {
        private TextView categoryName;
        private ImageView categoryImage;
        private Button title_image_btn;

        public ItemViewHolder(View itemView) {
            super(itemView);
            categoryName = (TextView) itemView.findViewById(R.id.categoryName);
            categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
            title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);
        }

        public void VideosItemClickListener(final int position, final LegacyVideoClickListener videosRVItemClickListener) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    videosRVItemClickListener.onItemClickListener(position);
                }
            });
        }

    }
}

And finally i am using this interface for listener :

public interface LegacyVideoClickListener {
    public void onItemClickListener(int position);
}

This procedure working fine all of my other portion of app but not working this case. I don't know where is the problem . Please help me .

回答1:

You this approach:

@Override 
    public void onBindViewHolder(final ViewHolder holder, int position) {
        final String element = mDataset[position];

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //your code 
            }
        });
    }


回答2:

Pass onVideosRVItemClickListener in your ItemViewHolder constructor.

@Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
        return new ItemViewHolder(view, onVideosRVItemClickListener);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, final int position) {
        Video video = videoList.get(position);
        Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
        holder.categoryName.setText(video.getTitle());
        holder.title_image_btn.setText(video.getDisplayType());

    }

    public class ItemViewHolder extends RecyclerView.ViewHolder {
        private TextView categoryName;
        private ImageView categoryImage;
        private Button title_image_btn;

        public ItemViewHolder(View itemView, final LegacyVideoClickListener videosRVItemClickListener) {
            super(itemView);
            categoryName = (TextView) itemView.findViewById(R.id.categoryName);
            categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
            title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    videosRVItemClickListener.onItemClickListener(getAdapterPosition());
                }
            });
        }

    }


回答3:

Check this sample

OnCLick can be achived using Custom Interface

interface Listener {
    void performOperation(int Position);
}

in Your Adapter

private Listener mListener;

In your Adapter initialize your listner in constructor like this

mListener = (Listener) context;

In your bindViewHolder method

holder.yourView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mListener.performOperation(position);
        }
    });

Now in your Activity implement that interface like this

public class LegacyHomeActivity extends ActivityBaseDrawer implements listner {

@Override
public void performOperation(int Position) {
    //Do whatever you want to do with this position
}

}


回答4:

Your interface adapter class should be like this

public class LegacyModeHomeAdapter extends RecyclerView.Adapter<LegacyModeHomeAdapter.ItemViewHolder> {
    private List<Video> videoList;
    private Context mContext;
    public static LegacyVideoClickListener onVideosRVItemClickListener;

    private LayoutInflater getLayoutInflater() {
        return LayoutInflater.from(mContext);
    }

    public LegacyModeHomeAdapter(Context mContext, LegacyVideoClickListener onVideosRVItemClickListener) {
        this.mContext = mContext;
        this.onVideosRVItemClickListener = onVideosRVItemClickListener;
    }

    public void setVideos(List<Video> videosList) {
        this.videoList = videosList;
        notifyDataSetChanged();
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = getLayoutInflater().inflate(R.layout.layout_legacy_mode_home_video_item, parent, false);
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, final int position) {
        Video video = videoList.get(position);
   Picasso.with(mContext).load(video.getThumb()).into(holder.categoryImage);
        holder.categoryName.setText(video.getTitle());
        holder.title_image_btn.setText(video.getDisplayType());
        holder.VideosItemClickListener(position, onVideosRVItemClickListener);
    }

    @Override
    public int getItemCount() {
        if (videoList != null) {
            return videoList.size();
        }
        return 0;
    }

    public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView categoryName;
        private ImageView categoryImage;
        private Button title_image_btn;

        public ItemViewHolder(View itemView) {
            super(itemView);
            categoryName = (TextView) itemView.findViewById(R.id.categoryName);
            categoryImage = (ImageView) itemView.findViewById(R.id.categoryImage);
            title_image_btn = (Button) itemView.findViewById(R.id.title_image_btn);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            onVideosRVItemClickListener.onItemClickListener(getPosition(), v);
        }
    }
    public void setOnItemClickListener(LegacyVideoClickListener clickListener) {
            LegacyModeHomeAdapter.onVideosRVItemClickListener = clickListener;
    }
    public interface LegacyVideoClickListener {
        public void onItemClickListener(int position, View v);
    }
}

And your adapter usage class should be like this

adapter.setOnItemClickListener(new LegacyModeHomeAdapter.LegacyVideoClickListener() {
        @Override
        public void onItemClick(int position, View v) {
            //Your code
        }
    });

Using this way of interface settings you can achieve the onclick listener function exactly. Please let me know if you are having trouble still.



回答5:

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public Button btMyButton;

        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
               // your implementation. In order to get position you can use `getAdapterPosition()` method               
       }
    }


回答6:

@Override
public void onBindViewHolder(RecyclerViewAdapter.ItemViewHolder holder, int position) {
        holder.name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

Try like this