在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();
            }

        }

    });

10-06 05:34