Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.