You need to enable JavaScript to run this app. 使用Firebase数据库的RecyclerView点击分类如何打开对应子分类新Activity
优惠活动
大模型
产品
解决方案
定价
更多

使用Firebase数据库的RecyclerView点击分类如何打开对应子分类新Activity

实现方案

1. 调整Firebase数据结构

优先优化数据存储结构,让父分类和子分类通过唯一key关联,避免传递全量数据,推荐结构如下:

{
  "category": {
    "-Nxyz123": { // Firebase自动生成的分类唯一key
      "name": "鸡肉",
      "description": "鸡肉类食谱汇总",
      "image": "xxx.jpg"
    },
    "-Nxyz456": {
      "name": "猪肉",
      "description": "猪肉类食谱汇总",
      "image": "yyy.jpg"
    }
  },
  "subCategory": {
    "-Nxyz123": { // 与父分类的唯一key一一对应,存储对应子分类
      "-Nabc123": {
        "name": "鸡胸肉食谱",
        "description": "低脂鸡胸肉做法",
        "image": "aaa.jpg"
      },
      "-Nabc456": {
        "name": "鸡腿食谱",
        "description": "多汁鸡腿做法",
        "image": "bbb.jpg"
      }
    },
    "-Nxyz456": {
      // 存储猪肉对应的子分类内容
    }
  }
}

2. 修改MainModel新增id字段

新增字段存储分类的唯一key,用于后续关联查询子分类:

public class MainModel {
    String id, name, description, image;
    MainModel() {}
    public MainModel(String id, String name, String description, String image) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.image = image;
    }
    // 新增id的get、set方法
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    // 原有name、description、image的get、set方法保留
}

3. 给MainAdapter添加点击回调

在适配器中定义点击事件接口,绑定列表项的点击逻辑:

public class MainAdapter extends FirebaseRecyclerAdapter<MainModel,MainAdapter.myViewHolder> {
    // 定义点击回调接口
    public interface OnCategoryClickListener {
        void onCategoryClick(String categoryId, String categoryName);
    }
    private OnCategoryClickListener listener;
    // 构造方法新增回调参数
    public MainAdapter(@NonNull FirebaseRecyclerOptions<MainModel> options, OnCategoryClickListener listener) {
        super(options);
        this.listener = listener;
    }
    @Override
    protected void onBindViewHolder(@NonNull MainAdapter.myViewHolder holder, int position, @NonNull MainModel model) {
        // 绑定Firebase生成的唯一key到model
        model.setId(getRef(position).getKey());
        holder.categoryName.setText(model.getName());
        holder.categoryDesc.setText(model.getDescription());
        Glide.with(holder.categoryImage.getContext())
                .load(model.getImage())
                .placeholder(R.drawable.common_google_signin_btn_icon_dark)
                .error(R.drawable.common_google_signin_btn_icon_dark_normal)
                .into(holder.categoryImage);
        // 绑定列表项点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCategoryClick(model.getId(), model.getName());
            }
        });
    }
    // 原有onCreateViewHolder、myViewHolder逻辑保持不变
}

4. 修改MainActivity配置跳转逻辑

初始化适配器时实现点击回调,仅传递必要的分类参数跳转子页面:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView = (RecyclerView)findViewById(R.id.recView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    FirebaseRecyclerOptions<MainModel> options =
            new FirebaseRecyclerOptions.Builder<MainModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("category"), MainModel.class)
                    .build();
    // 初始化适配器时传入点击回调
    mainAdapter = new MainAdapter(options, (categoryId, categoryName) -> {
        Intent intent = new Intent(MainActivity.this, SubCategoryActivity.class);
        // 仅传递分类id和名称两个字符串,无冗余数据
        intent.putExtra("category_id", categoryId);
        intent.putExtra("category_name", categoryName);
        startActivity(intent);
    });
    recyclerView.setAdapter(mainAdapter);
}
// 搜索方法也要同步修改适配器初始化逻辑
private void txtSearch(String str)
{
    FirebaseRecyclerOptions<MainModel> options =
            new FirebaseRecyclerOptions.Builder<MainModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("category").orderByChild("name").startAt(str).endAt(str+"~"), MainModel.class)
                    .build();
    mainAdapter = new MainAdapter(options, (categoryId, categoryName) -> {
        Intent intent = new Intent(MainActivity.this, SubCategoryActivity.class);
        intent.putExtra("category_id", categoryId);
        intent.putExtra("category_name", categoryName);
        startActivity(intent);
    });
    mainAdapter.startListening();
    recyclerView.setAdapter(mainAdapter);
}

5. 实现子分类页面SubCategoryActivity

子页面接收参数后,仅查询对应分类的子分类数据即可,逻辑和主页面几乎一致:

public class SubCategoryActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    SubCategoryAdapter subAdapter;
    String categoryId, categoryName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_category);
        // 接收传递过来的参数
        categoryId = getIntent().getStringExtra("category_id");
        categoryName = getIntent().getStringExtra("category_name");
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(categoryName);
        }
        recyclerView = findViewById(R.id.subRecView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 仅查询当前分类对应的子分类数据
        FirebaseRecyclerOptions<SubCategoryModel> options =
                new FirebaseRecyclerOptions.Builder<SubCategoryModel>()
                        .setQuery(FirebaseDatabase.getInstance().getReference().child("subCategory").child(categoryId), SubCategoryModel.class)
                        .build();
        subAdapter = new SubCategoryAdapter(options);
        recyclerView.setAdapter(subAdapter);
    }
    @Override
    protected void onStart() {
        super.onStart();
        subAdapter.startListening();
    }
    @Override
    protected void onStop() {
        super.onStop();
        subAdapter.stopListening();
    }
}

SubCategoryModel和SubCategoryAdapter的逻辑和主页面的对应类完全一致,按需匹配子分类字段即可。

方案优势

  • 跳转时仅传递两个字符串参数,无任何冗余数据,不会出现Intent传值大小超限问题
  • 子分类数据由对应页面独立拉取,不需要提前加载全量分类数据,降低首屏加载压力
  • 后续新增分类层级不需要调整传递逻辑,扩展性强

内容的提问来源于stack exchange,提问作者Jeremy Herrera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 08:57:03