发表于: 2018-11-05 23:11:48
0 883
一、今天完成的事情
查看护工信息
给RecyclerView的item添加点击事件
用了两种方法,第一种是在Adapter中添加
@Override
//onCreateViewHolder根据不同的viewType返回不同的布局
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.workerpost_item, parent, false);
final NormalViewHolder holder = new NormalViewHolder(view);
holder.normalView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
WorkerPost workerPost = workerList.get(position);
Log.d(TAG, "onClick: position = " + position);
String id = workerPost.getObjectId();
String name = workerPost.getWorkerName();
Log.d(TAG, "onCreate: id:" + id + " 姓名:" + name);
Intent intent = new Intent(v.getContext(), WorkerPageActivity.class);
intent.putExtra("id", id);
intent.putExtra("name", name);
v.getContext().startActivity(intent);
}
});
return new NormalViewHolder(view);
}
结果getAdapterPosition() 返回NO_POSITION(-1),暂时未解决。
2.为RecyclerView的每个子item设置setOnClickListener,然后在onClick中再调用一次对外封装的接口,将这个事件传递给外面的调用者
public interface OnItemClickListener {
void onItemClick(int position);
}
private OnItemClickListener onItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
@Override
//onCreateViewHolder根据不同的viewType返回不同的布局
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.workerpost_item, parent, false);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick((Integer) v.getTag());
}
}
});
return new NormalViewHolder(view);
}
在活动中
......
workerPostAdapter = new WorkerPostAdapter(getContext(), workerList);
workerPostAdapter.setOnItemClickListener(this);
......
@Override
public void onItemClick(int position) {
Log.d(TAG, "当前position: " + position);
WorkerPost workerPost = workerList.get(position);
String id = workerPost.getObjectId();
Log.d(TAG, "onCreate: id:" + id );
Intent intent = new Intent(getContext(), WorkerPageActivity.class);
intent.putExtra("id", id);
startActivity(intent);
}
二、明天计划的事情
1.完成查看雇主信息
2.在地图上查看护工、雇主位置
三、遇到的问题
RecycleView getAdapterPosition() 返回NO_POSITION(-1)
源码有两种种情况会返回NO_POSITION:
1.RecyclerView为空
public final int getAdapterPosition() {
return this.mOwnerRecyclerView == null ? -1 : this.mOwnerRecyclerView.getAdapterPositionFor(this);
}
2.当ViewHolder处于FLAG_REMOVED 等状态时会返回NO_POSITION
int getAdapterPositionFor(ViewHolder viewHolder) {
if (viewHolder.hasAnyOfTheFlags( ViewHolder.FLAG_INVALID
| ViewHolder.FLAG_REMOVED
| ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN
|| !viewHolder.isBound()) {
return RecyclerView.NO_POSITION;
}
return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition);
}
这两种情况都被我排除了(也可能没检查出来)
四、收获
评论