在android中同时对视图进行膨胀和绑定

问题描述 投票:1回答:1

我正在尝试为列表中的每个对象充气,并在同一时刻将其与数据绑定,这就是我实现这个的方法:

data.forEach { rule ->
        layoutInflater.inflate(
            R.layout.rule_view_holder,
            this.rulesContainer
        ).apply {
            setOnClickListener { content.flipVisibility() }
            title.text = rule.title
            contentText.text = rule.content.fromHtml()
            rule.images.map {
                createImageView(this.context, it)
            }.forEach {
                contentImages.addView(it)
            }
        }
    }

视图膨胀并正确插入到LinearLayout中,但似乎数据仅限于列表中的最后一项,这就是我的意思:image有列表中有6个项目,因此视图膨胀肯定是正确的(因为水平线,必须为每个视图充气)。

还有rule_view_holder布局screenshot

你能帮我修一下这个行为吗?

android kotlin layout-inflater
1个回答
0
投票

你可以在没有父项的情况下膨胀项目xml(传递null),然后调用addView

data.forEach { rule ->
    val view = layoutInflater.inflate(R.layout.rule_view_holder, null).apply {
        setOnClickListener { content.flipVisibility() }
        title.text = rule.title
        contentText.text = rule.content.fromHtml()
        rule.images.map {
            createImageView(this.context, it)
        }.forEach {
            contentImages.addView(it)
        }
    }
    this.rulesContainer.addView(view)
}
© www.soinside.com 2019 - 2024. All rights reserved.