Kotlin / anko

Pleasant Android application development
Apache License 2.0
15.89k stars 1.29k forks source link

Better documentation around dynamically generating UI #75

Open brennantaylor opened 9 years ago

brennantaylor commented 9 years ago

It is not very clear how to generate UI at arbitrary points in time. An example would be Adapters but also sometimes I want to generate UI dynamically to manually add to a ScrollView.

Also a common practice when inflating for an adapter is to pass the parent so the inflated view can inherit layout params and there does not appear to be an easy way to do this in anko.

I have been able to do these things but it took more experimentation than I feel is appropriate for something that is common to do in non-trivial applications.

androidovshchik commented 5 years ago

Hi

Have look at example

It works

class MenuListActivity : AppCompatActivity() {

    lateinit var list: LinearLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MenuListActivityUI().setContentView(this)
        addMenuItem("file:///android_asset/index.html", "HTML tests from assets")
    }

    private fun addMenuItem(url: String, title: String, bottomMargin: Int = 0) {
        val space = dip(16)
        with(AnkoContext.createDelegate(list)) {
            cardView {
                lparams(width = matchParent, height = wrapContent) {
                    setMargins(space, space, space, bottomMargin)
                }
                setOnClickListener {
                    startActivity(intentFor<AppCompatWebActivity>().apply {
                        putExtra(Constant.EXTRA_URL, url)
                    })
                }
                textView {
                    padding = space
                    textColor = Color.WHITE
                    textSize = 16f
                    text = title
                }.lparams(width = matchParent, height = wrapContent)
            }
        }
    }
}
class MenuListActivityUI : AnkoComponent<MenuListActivity> {

    override fun createView(ui: AnkoContext<MenuListActivity>): View = with(ui) {
        scrollView {
            lparams(width = matchParent, height = matchParent)
            owner.list = verticalLayout {
            }.lparams(width = matchParent, height = wrapContent)
        }
    }
}