如何重用anko组件并将其嵌套?

时间:2019-07-23 14:05:27

标签: android kotlin layout anko

我正在尝试制作可重复使用的anko组件并将它们嵌入其他anko组件中。在此示例中,我创建了一个ReusableComponent并将其放入MainActivityComponent中。结果是从不调用ReusableComponent的“ createView”方法。


//COMPONENT TO BE REUSED IN MORE SECTIONS
class ReusableComponent<T : Context>(val customize: AnkoContext<T>.() -> Unit = {}) : AnkoComponent<T> {

    lateinit var topImage: ImageView
    lateinit var title: TextView
    lateinit var description: TextView

    override fun createView(ui: AnkoContext<T>) = with(ui) {
        verticalLayout {
            topImage = imageView {
                backgroundColor = Color.GRAY
                scaleType = ImageView.ScaleType.CENTER_CROP
            }.lparams {
                height = dip(250)
                width = matchParent
            }

            title = textView {
                textAlignment = View.TEXT_ALIGNMENT_CENTER
                textSize = 22.0f
                minimumWidth = dip(150)
                padding = dip(10)
                backgroundColor = Color.GRAY
            }.lparams {
                topMargin = dip(10)
                width = wrapContent
                gravity = Gravity.CENTER_HORIZONTAL
            }

            description = textView {
                textSize = 16.0f
                backgroundColor = Color.GRAY
                minimumHeight = dip(250)
            }.lparams {
                topMargin = dip(10)
                leftMargin = dip(10)
                rightMargin = dip(10)
                bottomMargin = dip(10)
                width = matchParent
                height = wrapContent
            }
        }
    }

}

//COMPONENT OF THE MAIN ACTIVITY THAT USES THE REUSABLE COMPONENT
class MainActivityComponent : AnkoComponent<MainActivity> {

    lateinit var detail: DetailComponentUI<MainActivity>

    override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
        scrollView {
            verticalLayout {
                detail = ReusableComponent<MainActivity>()
            }.lparams {
                width = matchParent
                height = wrapContent
            }
        }
    }
}

//MAIN ACTIVITY CODE
class MainActivity : AppCompatActivity() {
    val ui = MainActivityUi()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ui.setContentView(this)
    }
}

关于为什么不调用该方法并且未创建ReusableComponent的视图,您有任何线索吗?

0 个答案:

没有答案