没有合适的资源?快使用搜索试试~ 我知道了~
首页解决RecyclerView无法onItemClick问题的两种方法
解决RecyclerView无法onItemClick问题的两种方法
6 下载量 75 浏览量
更新于2023-03-16
评论
收藏 288KB PDF 举报
主要介绍了解决RecyclerView无法onItemClick问题的相关知识,非常不错,具有参考借鉴价值,感兴趣的朋友一起看下吧
资源详情
资源评论
资源推荐
解决解决RecyclerView无法无法onItemClick问题的两种方法问题的两种方法
主要介绍了解决RecyclerView无法onItemClick问题的相关知识,非常不错,具有参考借鉴价值,感兴趣的朋友
一起看下吧
对于RecyclerView的使用,大家可以查看将替代ListView的RecyclerView 的使用详解(一),单单从代码结构来说RecyclerView
确实比ListView优化了很多,也简化了我们编写代码量,但是有一个问题会导致开发者不会去用它,更比说替换ListView了,
我不知道使用过RecyclerView的人有没有进一步查看,RecyclerView没有提供Item的点击事件,我们使用列表不仅仅为了显
示数据,同时也可以能会交互,所以RecyclerView这个问题导致基本没有人用它,我清楚谷歌是怎么想的,不过
RecyclerView也并没有把所有的路给堵死,需要我们写代码来实现Item的点击事件,我们都知道RecyclerView里面新加了
ViewHolder这个静态抽象类,这个类里面有一个方法getPosition()可以返回当前ViewHolder实例的位置,实现onItemClick就
是使用它来做的,下面有两种方法来实现:
第一种:不修改源码第一种:不修改源码
这种方法不修改源码,问题是只能在RecyclerView.Adapter中实现ItemClick事件
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.e("jwzhangjie", "当前点击的位置:"+getPosition());
}
});
}
}
这种方式直观上看起来不太好,不过也可以实现ItemClick事件。
第二种方法:修改第二种方法:修改RecyclerView源码源码
1、把在、把在RecyClerView类里面定义类里面定义OnItemClickListener接口接口
/**
* Interface definition for a callback to be invoked when an item in this
* RecyclerView.Adapter has been clicked.
*/
public interface OnItemClickListener {
/**
* Callback method to be invoked when an item in this RecyclerView.Adapter has
* been clicked.
* <p>
* Implementers can call getPosition(position) if they need
* to access the data associated with the selected item.
*
* @param view The view within the RecyclerView.Adapter that was clicked (this
* will be a view provided by the adapter)
* @param position The position of the view in the adapter.
*/
void onItemClick(View view, int position);
}
public static OnItemClickListener mOnItemClickListener = null;
/**
* Register a callback to be invoked when an item in this AdapterView has
* been clicked.
*
* @param listener The callback that will be invoked.
*/
public void setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
}
/**
* @return The callback to be invoked with an item in this AdapterView has
* been clicked, or null id no callback has been set.
*/
public final OnItemClickListener getOnItemClickListener() {
return mOnItemClickListener;
}
2、在、在RecyclerView中的抽象类中的抽象类ViewHolder中添加中添加View的点击事件的点击事件
public static abstract class ViewHolder implements OnClickListener{
public final View itemView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
/**
* This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType
* are all valid.
*/
static final int FLAG_BOUND = 1 << 0;
/**
* The data this ViewHolder's view reflects is stale and needs to be rebound
* by the adapter. mPosition and mItemId are consistent.
*/
static final int FLAG_UPDATE = 1 << 1;
/**
* This ViewHolder's data is invalid. The identity implied by mPosition and mItemId
* are not to be trusted and may no longer match the item view type.
* This ViewHolder must be fully rebound to different data.
*/
static final int FLAG_INVALID = 1 << 2;
/**
* This ViewHolder points at data that represents an item previously removed from the
* data set. Its view may still be used for things like outgoing animations.
*/
static final int FLAG_REMOVED = 1 << 3;
/**
* This ViewHolder should not be recycled. This flag is set via setIsRecyclable()
* and is intended to keep views around during animations.
*/
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
private int mFlags;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(itemView, getPosition());
}
}
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
this.itemView.setOnClickListener(this);
}
void offsetPosition(int offset) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
mPosition += offset;
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
}
public final int getPosition() {
return mOldPosition == NO_POSITION ? mPosition : mOldPosition;
}
public final long getItemId() {
return mItemId;
}
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
mScrapContainer = null;
}
void setScrapContainer(Recycler recycler) {
mScrapContainer = recycler;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void clearFlagsForSharedPool() {
mFlags = 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{" +
Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId);
if (isScrap()) sb.append(" scrap");
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
sb.append("}");
return sb.toString();
}
3、完成上面的步骤,就可以使用、完成上面的步骤,就可以使用RecyclerView来完成来完成itemClick事件了事件了
cashAccountList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
AppLog.e("position: "+position);
}
});
下面是完整的RecyclerView源码:
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v7.widget;
import android.content.Context;
import android.database.Observable;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.Pools;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v4.widget.ScrollerCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* A flexible view for providing a limited window into a large data set.
*
* <h3>Glossary of terms:</h3>
*
* <ul>
* <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views
* that represent items in a data set.</li>
* <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li>
* <li><em>Index:</em> The index of an attached child view as used in a call to
* {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li>
* <li><em>Binding:</em> The process of preparing a child view to display data corresponding
* to a <em>position</em> within the adapter.</li>
* <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter
* position may be placed in a cache for later reuse to display the same type of data again
* later. This can drastically improve performance by skipping initial layout inflation
* or construction.</li>
* <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached
* state during layout. Scrap views may be reused without becoming fully detached
* from the parent RecyclerView, either unmodified if no rebinding is required or modified
* by the adapter if the view was considered <em>dirty</em>.</li>
* <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before
* being displayed.</li>
* </ul>
*/
public class RecyclerView extends ViewGroup {
private static final String TAG = "RecyclerView";
private static final boolean DEBUG = false;
private static final boolean ENABLE_PREDICTIVE_ANIMATIONS = false;
private static final boolean DISPATCH_TEMP_DETACH = false;
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
public static final int NO_POSITION = -1;
public static final long NO_ID = -1;
public static final int INVALID_TYPE = -1;
private static final int MAX_SCROLL_DURATION = 2000;
private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
private final Recycler mRecycler = new Recycler();
private SavedState mPendingSavedState;
/**
* Note: this Runnable is only ever posted if:
* 1) We've been through first layout
* 2) We know we have a fixed size (mHasFixedSize)
* 3) We're attached
*/
private final Runnable mUpdateChildViewsRunnable = new Runnable() {
public void run() {
if (mPendingUpdates.isEmpty()) {
return;
}
eatRequestLayout();
updateChildViews();
resumeRequestLayout(true);
}
};
private final Rect mTempRect = new Rect();
private final ArrayList<UpdateOp> mPendingUpdates = new ArrayList<UpdateOp>();
private final ArrayList<UpdateOp> mPendingLayoutUpdates = new ArrayList<UpdateOp>();
private Pools.Pool<UpdateOp> mUpdateOpPool = new Pools.SimplePool<UpdateOp>(UpdateOp.POOL_SIZE);
private Adapter mAdapter;
private LayoutManager mLayout;
private RecyclerListener mRecyclerListener;
private final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<ItemDecoration>();
private final ArrayList<OnItemTouchListener> mOnItemTouchListeners =
new ArrayList<OnItemTouchListener>();
private OnItemTouchListener mActiveOnItemTouchListener;
private boolean mIsAttached;
private boolean mHasFixedSize;
private boolean mFirstLayoutComplete;
private boolean mEatRequestLayout;
private boolean mLayoutRequestEaten;
private boolean mAdapterUpdateDuringMeasure;
private final boolean mPostUpdatesOnAnimation;
private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
ItemAnimator mItemAnimator = new DefaultItemAnimator();
private static final int INVALID_POINTER = -1;
/**
* The RecyclerView is not currently scrolling.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_IDLE = 0;
/**
* The RecyclerView is currently being dragged by outside input such as user touch input.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_DRAGGING = 1;
/**
* The RecyclerView is currently animating to a final position while not under
* outside control.
* @see #getScrollState()
*/
public static final int SCROLL_STATE_SETTLING = 2;
// Touch/scrolling handling
private int mScrollState = SCROLL_STATE_IDLE;
private int mScrollPointerId = INVALID_POINTER;
private VelocityTracker mVelocityTracker;
private int mInitialTouchX;
private int mInitialTouchY;
private int mLastTouchX;
private int mLastTouchY;
private final int mTouchSlop;
private final int mMinFlingVelocity;
private final int mMaxFlingVelocity;
private final ViewFlinger mViewFlinger = new ViewFlinger();
private final State mState = new State();
private OnScrollListener mScrollListener;
// For use in item animations
boolean mItemsAddedOrRemoved = false;
boolean mItemsChanged = false;
int mAnimatingViewIndex = -1;
int mNumAnimatingViews = 0;
boolean mInPreLayout = false;
private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
new ItemAnimatorRestoreListener();
private boolean mPostedAnimatorRunner = false;
private Runnable mItemAnimatorRunner = new Runnable() {
@Override
public void run() {
if (mItemAnimator != null) {
mItemAnimator.runPendingAnimations();
}
mPostedAnimatorRunner = false;
}
};
private static final Interpolator sQuinticInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final int version = Build.VERSION.SDK_INT;
mPostUpdatesOnAnimation = version >= 16;
final ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
mItemAnimator.setListener(mItemAnimatorListener);
}
/**
* RecyclerView can perform several optimizations if it can know in advance that changes in
* adapter content cannot change the size of the RecyclerView itself.
* If your use of RecyclerView falls into this category, set this to true.
*
* @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
*/
public void setHasFixedSize(boolean hasFixedSize) {
mHasFixedSize = hasFixedSize;
}
剩余69页未读,继续阅读
weixin_38532139
- 粉丝: 5
- 资源: 911
上传资源 快速赚钱
- 我的内容管理 收起
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
会员权益专享
最新资源
- zigbee-cluster-library-specification
- JSBSim Reference Manual
- c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf
- 建筑供配电系统相关课件.pptx
- 企业管理规章制度及管理模式.doc
- vb打开摄像头.doc
- 云计算-可信计算中认证协议改进方案.pdf
- [详细完整版]单片机编程4.ppt
- c语言常用算法.pdf
- c++经典程序代码大全.pdf
- 单片机数字时钟资料.doc
- 11项目管理前沿1.0.pptx
- 基于ssm的“魅力”繁峙宣传网站的设计与实现论文.doc
- 智慧交通综合解决方案.pptx
- 建筑防潮设计-PowerPointPresentati.pptx
- SPC统计过程控制程序.pptx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0