假设你具有一个如下所示的Firestore数据库结构:
Firestore-root | --- products (collection)|--- documentIdOne (document)| || --- productName: "Milk"|--- documentIdTwo (document)| || --- productName: "Soy Milk"|--- documentIdThree (document) | --- productName: "Bacon"
看起来也像这样的模型类:
public class ProductModel { private String productName; public ProductModel() {} public ProductModel(String productName) {this.productName = productName;} public String getProductName() {return productName;}}.XML包含的文件
RecyclerView也如下所示:
<android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recycler_view"/>
要显示所有产品名称,请按照以下步骤操作。
首先,你需要RecyclerView在你的活动中找到并进行如下设置LinearLayoutManager:
RecyclerView recyclerView = findViewById(R.id.recycler_view);recyclerView.setLayoutManager(new LinearLayoutManager(this));
然后,你需要创建Firestore数据库的根引用以及Query类似这样的对象:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();Query query = rootRef.collection("products") .orderBy("productName", Query.Direction.ASCENDING);然后,你必须创建一个FirestoreRecyclerOptions像这样的对象:
FirestoreRecyclerOptions<ProductModel> options = new FirestoreRecyclerOptions.Builder<ProductModel>() .setQuery(query, ProductModel.class) .build();
在活动类中,创建一个如下所示的holder类:
private class ProductViewHolder extends RecyclerView.ViewHolder { private View view; ProductViewHolder(View itemView) { super(itemView); view = itemView; } void setProductName(String productName) { TextView textView = view.findViewById(R.id.text_view); textView.setText(productName); }}然后创建一个adapter声明为全局的:
private FirestoreRecyclerAdapter<ProductModel, ProductViewHolder> adapter;
并在你的活动中实例化它,如下所示:
adapter = new FirestoreRecyclerAdapter<ProductModel, ProductViewHolder>(options) { @Override protected void onBindViewHolder(@NonNull holder productViewHolder, int position, @NonNull ProductModel productModel) { holder.setProductName(productModel.getProductName()); } @NonNull @Override public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product, parent, false); return new ProductViewHolder(view); }};recyclerView.setAdapter(adapter);最后,不要忘记重写以下两个方法并开始侦听更改:
@Overrideprotected void onStart() { super.onStart(); adapter.startListening();}@Overrideprotected void onStop() { super.onStop(); if (adapter != null) { adapter.stopListening(); }}结果是这样的:
编辑:
如果你想在用户单击某项时显示一条祝酒消息,请setProductName()在ProductViewHolder该类的方法内添加以下代码行:
textView.setonClickListener(new View.onClickListener() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), productName, Toast.LENGTH_SHORT).show(); }});


