[英]getRef(position).getKey() in RecyclerView.Adapter
在FirebaseRecyclerAdapter中,我可以使用getRef(position).getKey()
但我使用的是RecyclerView.Adapter,只要用户单击复选框,我都希望获取密钥。 这是我在onBindViewHolder()中的代码:
@Override
public void onBindViewHolder(@NonNull UsersViewHolders holder, final int position) {
holder.setName(mUserNameList.get(position));
holder.setDesc(mUserDescList.get(position));
holder.setImage(mUserPicList.get(position));
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//TODO: get the key
}
});
}
是否可以在RecyclerView.Adapter中获取密钥?
我只是通过重构代码来解决自己的问题。
1.在适配器类中,我为itemClickListener创建了一个接口
public interface RecyclerViewItemClick {
public void OnItemClickListener(UsersViewHolders holder, int position);
}
并创建一个全球
private RecyclerViewItemClick mListener;
将其添加到构造函数
public MessageListAdapter(RecyclerViewItemClick listener) {
this.mListener = listener;
}
2.在onBindViewHolder()中,我传递了持有人和位置
@Override
public void onBindViewHolder(@NonNull final UsersViewHolders holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mListener.OnItemClickListener(holder, position);
}
});
}
3.在您的活动中,添加此代码。 为ArrayList声明一个全局变量以存储键,然后将addListenerForSingleValueEvent调用到DatabaseReference
//mUserDatabase is a DatabaseReference
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String uid = datas.getKey();
//mUserKey is an ArrayList<String>
mUserKey.add(uid);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
4.现在添加它以获取每个位置的钥匙
mAdapter = new MyAdapter(new MyAdapter.RecyclerViewItemClick() {
@Override
public void OnItemClickListener(PickMemberAdapter.UsersViewHolders holder, int position) {
String userKey = mUserKey.get(position);
if (!holder.mCheckBox.isChecked()) {
holder.mCheckBox.setChecked(true);
Toast.makeText(MainActivity.this, userKey, Toast.LENGTH_LONG).show();
} else {
holder.mCheckBox.setChecked(false);
Toast.makeText(MainActivity.this, userKey, Toast.LENGTH_LONG).show();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.