使用介面實現RecyclerView中的item點選事件

yuzhong_沐陽發表於2018-04-03

實現思路:在Adapter中編寫介面,在MainActivity中實現跳轉


一:Adapter

定義一個介面

public interface OnItemClickListener {
        void onClick(View view,int position);
    }

定義一個方法

private OnItemClickListener mOnItemClickListener = null;
    public void setOnItemClickListener (OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

在OnBindView中給Item編寫點選事件

        if (mOnItemClickListener != null){
            holder.newsItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onClick(v,position);
                }
            });
        }

二:MainActivity

實現跳轉

        NewsAdapter newsAdapter = new NewsAdapter(this,mNewsList);
        newsAdapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("news_url",mNewsList.get(position).getNewsUrl());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

相關文章