Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Kotlin and Anko Learning Anko Placing the Button

Raveesh Agarwal
Raveesh Agarwal
2,994 Points

Can't assign the ID in this way

Hi, I am using Anko 0.10.1 When I try to assign id under textView block as id = 11, the compiler shows Anko runtime exception, please check.

2 Answers

Ok looks like you need to define a val to assign it, maybe is because it only accept inmutable values on ID's.

import org.jetbrains.anko.relativeLayout
import org.jetbrains.anko.textView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        var counter = 0
        val ID_OK = 11
        relativeLayout(){
            val counterTextView = textView {
                id = ID_OK
                text = "0"
                textSize = 24f
            }

            button {
                setOnClickListener {
                    counter++
                    counterTextView.text = counter.toString()
                }
            }.lparams {
                below(counterTextView)
            }

        }
    }
}
Raveesh Agarwal
Raveesh Agarwal
2,994 Points
import org.jetbrains.anko.relativeLayout
import org.jetbrains.anko.textView

class MainActivity : AppCompatActivity() {

    @SuppressLint("ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        var counter = 0
        relativeLayout(){
            val counterTextView = textView {
                id = 11
                text = "0"
                textSize = 24f
            }

            button {
                setOnClickListener {
                    counter++
                    counterTextView.text = counter.toString()
                }
            }.lparams {
                below(counterTextView)
            }

        }
    }
}

adding @SuppressLint("ResourceType") made the error go away.

It works but thats not the correct way to solve things.