2 回答

TA貢獻1866條經驗 獲得超5個贊
如果您嘗試在position方法中確定項目的 Firebase 數據庫 ID onBindViewHolder,則必須自己維護該映射。您可以通過從快照中提取getKey()和并保留它們的列表來輕松地做到這一點。getValue()onDataChange
是這樣的:
mProductKeys = new ArrayList<String>();
mDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapShot : dataSnapshot.getChildren())
{
Product product = postSnapShot.getValue(Product.class);
mProducts.add(product);
mProductKeys.add(postSnapShot.getKey());
}
mAdapter = new ProductsAdapter(ProductsActivity.this, mProducts);
mRecyclerView.setAdapter(mAdapter);
mProgressBar.setVisibility(View.INVISIBLE);
}
然后在 中,onBindViewHolder您可以查找在 中單擊的項目的鍵mProductKeys。

TA貢獻1895條經驗 獲得超7個贊
好的,我嘗試了不同的方法,只需添加一行即可完成。:) 無需添加ArrayList<String>。
? ? @Override
? ? public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
? ? ? ? for (DataSnapshot postSnapShot : dataSnapshot.getChildren())
? ? ? ? {
? ? ? ? ? ? Product product = postSnapShot.getValue(Product.class);
? ? ? ? ? ? product.setpKey(postSnapShot.getKey());
? ? ? ? ? ? mProducts.add(product);
? ? ? ? }
? ? ? ? mAdapter = new ProductsAdapter(ProductsActivity.this, mProducts);
? ? ? ? mRecyclerView.setAdapter(mAdapter);
? ? ? ? mProgressBar.setVisibility(View.INVISIBLE);
? ? }
并添加String pKey到我的Product.classwith Setter and Getter。
添加回答
舉報