I created a Quiz application in android and used TextView as buttons in Answers option but its not working and i don't know what I have done wrong in my code.
override fun onClick(v: View?) {
when(v?.id) {
R.id.tvOptionOne -> {
selectedOptionView(binding.tvOptionOne,1)
}
R.id.tvOptionTwo -> {
selectedOptionView(binding.tvOptionTwo,2)
}
R.id.tvOptionThree -> {
selectedOptionView(binding.tvOptionThree,3)
}
R.id.tvOptionFour -> {
selectedOptionView(binding.tvOptionFour, 4)
}
R.id.btnSubmit -> {
if (mSelectedOptionPosition == 0){
mCurrentPossition++
when{
mCurrentPossition <= mQuestionList!!.size -> {
setQuestion()
}else ->{
Toast.makeText(this, "You have successfully compelted the quiz", Toast.LENGTH_SHORT).show()
}
}
}else{
val question = mQuestionList?.get(mCurrentPossition -1)
if (question!!.correctAnswer != mSelectedOptionPosition){
answerView(mSelectedOptionPosition, R.drawable.wrong_option_border_bg)
}
answerView(question.correctAnswer, R.drawable.correct_option_border_bg)
if (mCurrentPossition == mQuestionList!!.size){
binding.btnSubmit.text = "FINISH"
}else{
binding.btnSubmit.text = "GO TO NEXT QUESTION"
}
mSelectedOptionPosition == 0
}
}
}
}
private fun selectedOptionView(tv: TextView, seletedOptionNum:Int){
defaultOptionsView()
mSelectedOptionPosition = seletedOptionNum
tv.setTextColor(Color.parseColor("#363A43"))
tv.setTypeface(tv.typeface, Typeface.BOLD)
tv.background = ContextCompat.getDrawable(this, R.drawable.selected_option_border_bg)
}
This code should have resulted in highlight the clicked answer box but it shows nothing after clicking.enter image description here
Add this below code to your onCreate
(for Activity), onViewCreated
(for Fragment)
tvOptionOne.setOnClickListener(this)
tvOptionTwo.setOnClickListener(this)
tvOptionThree.setOnClickListener(this)
tvOptionFour.setOnClickListener(this)