大部分的人都是使用onclicklistener直接在viewholder裡面去實作,不過這真的很困擾,
因為click的動作就得跟viewholder綁在一起
寫法大概如下
public class LineViewHolder extends RecyclerView.ViewHolder {
private final TextView textView;
public LineViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.info_text);
}
public void bindview(int pos) {
textView.setText("pos " + pos);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
}
}另一部份的人應該都是將onclicklistener直接從adapter 一路往下帶
寫法大概如下
public class LineViewHolder extends RecyclerView.ViewHolder {
private final TextView textView;
private OnClickListener mListener;
public LineViewHolder(View itemView, OnClickListener listener) {
super(itemView);
mListener = listener;
textView = (TextView) itemView.findViewById(R.id.info_text);
}
public void bindview(int pos) {
textView.setText("pos " + pos);
itemView.setOnClickListener(mListener);
}
}最近看到一個有趣的寫法,在這邊分享給大家
他使用了addOnItemTouchListener,特別之處在於他的寫法有點像是
listview的setOnItemclick ,不再需要將listener一路往下帶到viewholder或是寫在viewholder裡讓其他人都找不到了XD
mDetector = new GestureDetectorCompat(this, new RecyclerViewOnGestureListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Ted","onclick");
}
}));
mRecyclerview.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mDetector.onTouchEvent(e);
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
private class RecyclerViewOnGestureListener extends GestureDetector.SimpleOnGestureListener {
private View.OnClickListener mOnclick;
public RecyclerViewOnGestureListener(View.OnClickListener onClickListener){
mOnclick = onClickListener;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
View view = mRecyclerview.findChildViewUnder(e.getX(), e.getY());
int position = mRecyclerview.getChildPosition(view);
// handle single tap
if(mOnclick!= null){
mOnclick.onClick(view);
}
return super.onSingleTapConfirmed(e);
}
}
不過,目前看到這樣的寫法還是會有問題,由於是使用touchevent並不是真的click行為,所以現實上還是有差距的,如果真的要做到一樣的click的話,就必須將view裡面的touch行為複製出來實作了….不過如果只是單純的singleTap行為,就可以利用這種快速的做法來完成囉~
沒有留言:
張貼留言