1.为什么在RecyclerView取消掉了Listview里的OnItemClickListner事件,
简单来说就是因为ListView里的OnItemClickListner与OnClickListner
发生了冲突,OnItemClickListner无法解决多种多样的事件,
所以在Recycerview里面便去掉了OnitemClickListner的方法
2.如何给Recycerview添加监听事件???
一般可以想到的方法有两种,关键的关键就是如何去获取position,第一种方法就是在适配器里面getPosition(),但是这个getPosition()已经过时了,但还有一种方法,对外实现接口,下面就是这个封装了的工具类的代码:
package com.example.com.mlsdome.Activity.Util;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by 12697 on 2017/3/19.
*/
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener
{
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
});
}
@Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildPosition(childView));
return true;
}
return false;
}
@Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept)
{
}
}
剩下的就简单了
md_rView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position)
{
switch (position)
{
case 0:
Intent intent=new Intent(MatchDetailsActivity.this,WebViewActivity.class);
intent.putExtra("url","http://www.myexception.cn/mobile/1952989.html");
startActivity(intent);
break;
}
}
}));
OK,到这里就完成了