Home > database >  how to assign a condition to an imageView by using if else?
how to assign a condition to an imageView by using if else?

Time:07-03

I tried to show a random imageView out of 2(one,two) with this binding.imageView.setImageResource(oneandtwo[random.nextInt(oneandtwo.size)]) it works fine and

i wanted to increase score when i clicked on imageView but score increases independent to that, sometimes increases when i clicked on imageView2 and sometimes imageView, i want to increase score when i only clicked on imageView. i couldnt figure out. Thanks in advance.

    var score = 0
    val oneandtwo: IntArray = intArrayOf(
        R.drawable.ic_baseline_looks_one_24,
        R.drawable.ic_baseline_looks_two_24
    )

binding.imageView.setOnClickListener{
            val random = Random
            binding.imageView.setImageResource(oneandtwo[random.nextInt(oneandtwo.size)])
            if (oneandtwo[random.nextInt(oneandtwo.size)]==(R.drawable.ic_baseline_looks_one_24)){
                score  
                binding.textView.text = score.toString()
            }
}

CodePudding user response:

The number you gave in the image and the number you checked in the if block may not match and will not give the result you want. If you change code like this. Probably your problem will be solved.

binding.imageView.setOnClickListener{
        val random = Random().nextInt(oneandtwo.size)
        binding.imageView.setImageResource(oneandtwo[random])
        if (oneandtwo[random]==(R.drawable.ic_baseline_looks_one_24)){
            score  
            binding.textView.text = score.toString()
        }

}

CodePudding user response:

What you are doing is checking the resourceId of the newly generated image, not the one you just clicked. That's why it not giving the result you want ,i.e, increment on the click of imageView and not on click of imageView2. Try below code. it should work

var score = 0
val oneandtwo: IntArray = intArrayOf(R.drawable.ic_baseline_looks_one_24,R.drawable.ic_baseline_looks_two_24)

/*Initalize the initial image and tag either here or in xml file*/
val random = Random().nextInt(oneandtwo.size)
binding.imageView.setImageResource(oneandtwo[random])
binding.imageView.Tag = oneandtwo[random]


binding.imageView.setOnClickListener{

    val imageTag = binding.imageView.Tag
    if (imageTag == (R.drawable.ic_baseline_looks_one_24)) {
       score  
       binding.textView.text = score.toString()
    }
 
    val random = Random().nextInt(oneandtwo.size)
    binding.imageView.setImageResource(oneandtwo[random])
    binding.imageView.Tag = oneandtwo[random]
}
  • Related