Kaan
Kaan

Reputation: 5

Add iterator to id --> R.id.+i+

i have 8 checkboxes and i want to know which ones are enabled when button clicked. So first i tried the method below. Checkbox ids: c1, c2, c3...

saveBtn.setOnClickListener {
            for(i in 1..8){
               var tempId = "R.id.c"+i+""
                if(findViewById<CheckBox>(tempId.toInt()).isEnabled){

                }

            }
}

And i got the error: FATAL EXCEPTION: main java.lang.NumberFormatException: For input string: "R.id.c1"

I realized that toInt() method is useless cause tempId contain letters.
Then i got the checkbox's real id its like this: 2131165251 and change the tempId variable with this. But same error again.
Now i did it different way but still curious about why doesn't work method above?

Upvotes: 0

Views: 29

Answers (1)

Blackbelt
Blackbelt

Reputation: 157467

you can use Resources.getIdentifier() to retrieve the id you are looking for

val id = resources.getIdentifier("c$i", "id", context.packageName)

Upvotes: 1

Related Questions