0

I'm new to anko and I'm loving it already. However, I can't seem to find a way to access the defined values within my UI design from my activity.

Here's an example:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        MainActivityUI().setContentView(this)
    }
}



class MainActivityUI :AnkoComponent<MainActivity> {
    override fun createView(ui: AnkoContext<MainActivity>) = with(ui){
        frameLayout {
            var textDisplay = textView {
                text = "Hello World"
            }.lparams {
                width = wrapContent
                height = wrapContent
                gravity = Gravity.CENTER
            }
        }
    }
}

Let's say I want to be able to set the string value for textDisplay from my MainActivity. If I was doing this in xml, I could just go ahead and use find.View.by.id and use setText and the job will be done. However, I can't seem to find any solution for this in anko.

I've read from another stackoverflow post that I can use lateinit var to declare like a global variable and then access it from anywhere. But then is this the only way to do it?

I mean, sure I can have all my UI function codes to be within the UI activity. But this will become very messy if the project grows bigger, and I'm trying to separate my UI design from my function code.

Any help will be grateful. Thanks

edit 1: changed to var for changeable action

fireboy0526
  • 129
  • 1
  • 1
  • 12
  • 1
    To be honest anko layouts is a nice thing for small layouts like dialogs, but xml design beats it in every other usecase. From the designer to support for different screen sizes and reuse of layouts it is just better. Also with kotlin-android-extensions it is a breeze to use. Also it promotes a better separation between design any business-logic. And yes `lateinit var` works just fine for what you do. – leonardkraemer Oct 27 '18 at 08:03
  • Thank you for your reply. If **lateinit var** is the only solution to go, I might switch back to xml for now. – fireboy0526 Oct 27 '18 at 08:20

0 Answers0