Kotlin:在多项选择测验中随机排列答案 Answer.kt Question.kt

问题描述

我已经在Kotlin中创建了一个多项选择测验。我想在每个问题中随机排列答案,并确定正确答案的新位置,以对照用户提交的答案。我创建了一个随机播放功能,但是不确定如何正确实现它。任何帮助将不胜感激。

有问题的对象

/logout

数据类

object ConstantsAnalysis {
        const val TOTAL_CORRECT: String = "total_correct"
        const val TOTAL_OPP: String = "total_opp"
        fun getQuestions3(): ArrayList<Questions3> {
            val questionList = ArrayList<Questions3>()
            val q1 = Questions3(1,null,"On a graph,the horizontal line along which data are plotted is the _____","y axis","x axis","origin","quadrant",2,R.string.Jones_1997,null)

            val q2 = Questions3(2,the vertical line along which data are plotted is the _____",1,R.string.Holmes_1977)

            questionList.addAll(listOf(q1,q2))
            questionList.shuffle()
            return questionList
        }
    }

问题活动

data class Questions3(val id: Int,val image: Int?,val question: String,val option1: String,val option2: String,val option3: String,val option4: String,val correctAnswer: Int,val dialogBox: Int?,val dialogBox2: Int?)

解决方法

通过将QuestionAnswer分开来分离对象是一种很好的方法。 我的意思是,您可以将自定义答案对象列表放到列表中,而不是在问题中使用字符串列表作为答案

更具体地说,您必须创建一个像这样的答案类。

Answer.kt

data class Answer(
        val answer: String,val isCorrect: Boolean,// You can add other attributes
)

然后,您必须将Question类更改为这样

Question.kt

data class Question(
        val id: Int,val image: Int?,val answers: MutableList<Answer>,// or You can add them as 4 separate answer objects
        val dialogBox: Int?,val dialogBox2: Int?
)

然后,通过获取用户选择并呼叫的答案,可以更轻松地随机播放和识别正确答案

if (answer.isCorrect()){
   // Whatever
}

通过实现这一点,改组将像

val question = Question( /* Question Defenition*/)
question.answers.shuffle()

编辑

例如,您可以在MainActivity onCreate

中定义这样的问题
val answersList1 = mutableListOf(
    Answer("answer1",false),Answer("answer2",Answer("answer3",true),// This is the correct answer
    Answer("answer4",)
val question1 = Question(
    id = 0,image = R.drawable.image,answers = answersList,dialogBox = 1,dialogBox2 = 2
)

然后通过更改其Radio属性来重命名RadioButton,或者如果您使用的是TextViews,也可以重命名它们。


radio_button0.text = answersList1[0].answer
radio_button1.text = answersList1[1].answer
// add 4 radio buttons

然后在您的onClick回调中,您可以触发点击并确定正确的答案

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.radio_button0 -> {
            if (answersList1[0].isCorrect)
            // the answer is correct
        }
        R.id.radio_button1 -> {
            if (answersList1[1].isCorrect)
                // the answer is correct
                // Do something
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...