You need to enable JavaScript to run this app. Kotlin Android开发:如何按分类筛选题目并跳转至答题页展示
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Android开发:如何按分类筛选题目并跳转至答题页展示

实现步骤

1. 修正CategoryActivity的点击跳转逻辑

你当前的点击事件里仅传递了分类名称,缺少和题目关联的分类ID,且getQuestionsByCategory方法不需要在当前页面调用,修改onItemClick代码如下:

override fun onItemClick(item: CategoryModel, position: Int) {
    Toast.makeText(this, "${item.name} Quiz Selected ", Toast.LENGTH_SHORT).show()
    Intent(this, QuizQuestionActivity::class.java).also { intent ->
        // 同时传递分类ID和分类名称
        intent.putExtra("CATEGORY_ID", item.id)
        intent.putExtra("CATEGORY_NAME", item.name)
        startActivity(intent)
    }
}

你可以删掉CategoryActivity里占位的getQuestionsByCategory方法,过滤逻辑放到目标页面处理即可。

2. 按分类ID过滤题目列表

推荐先在Constants类中封装按分类查题的工具方法,方便全局调用,修改后的Constants代码如下:

object Constants {
    // 你原来的getQuestions方法保持不变
    fun getQuestions(): ArrayList<Question> {
        // 原有代码无需改动
    }

    // 新增按分类ID获取题目的方法
    fun getQuestionsByCategory(categoryId: Int): ArrayList<Question> {
        return getQuestions().filter { it.categoryId == categoryId } as ArrayList<Question>
    }
}

3. QuizQuestionActivity接收参数并获取题目列表

在QuizQuestionActivity的onCreate方法中先接收传递的参数,再获取对应分类的题目:

private lateinit var currentQuestionList: ArrayList<Question>
private lateinit var categoryName: String

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // 你的viewBinding初始化逻辑不变

    // 接收参数
    val categoryId = intent.getIntExtra("CATEGORY_ID", -1)
    categoryName = intent.getStringExtra("CATEGORY_NAME") ?: "未知分类"

    // 参数异常处理
    if (categoryId == -1) {
        Toast.makeText(this, "分类参数错误", Toast.LENGTH_SHORT).show()
        finish()
        return
    }

    // 获取当前分类所有题目
    currentQuestionList = Constants.getQuestionsByCategory(categoryId)

    // 后续逻辑:根据你的业务需求渲染题目即可,比如单题逐页展示、或者用RecyclerView展示全部题目列表
}

内容的提问来源于stack exchange,提问作者Michael Prince

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:09:03