anko - 来自单独类的调用函数

时间:2018-05-30 05:18:10

标签: android kotlin anko

我正在尝试了解如何在使用Anko时从单独的类调用函数。

我尝试了各种策略,但又回到了Anko Component文档示例

class UserOrder : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        UserOrderUI().setContentView(this)
    }
}

class UserOrderUI : AnkoComponent<UserOrder> {
    override fun createView(ui: AnkoContext<UserOrder>) = with(ui) {
        val util = Util()
        verticalLayout {
            val name = editText()
            button("Say Hello") {
            }
            linearLayout {
                util.test()
            }

        }
    }

}

class Util{
    fun _LinearLayout.test(){
        button("Say Hello") {
        }
    }
}

util.test()附近的上述代码表示无法找到该函数。

我的问题是:如何从一个单独的类调用函数(以鼓励代码重用)返回一个布局(verticalLayout用于此目的)

例如:

fun getLayout(): LinearLayout {
    return linearLayout {
        //stuff in here
    }
}

我有时会收到View已经设置的错误,或者Child已经有了父级,我需要先在父级上使用removeView()。

1 个答案:

答案 0 :(得分:0)

问题在于您将_LinearLayout.test定义为Util Util。这意味着它只能在util实例的上下文中访问。另请注意,您尝试在_LinearLayout上调用该方法,这并不完全正确。它仅针对接收器类型with定义。

幸运的是,范围功能让您可以使用其他对象&#39;范围和linearLayout { with(util){ test() } } 建议在这里:

{{1}}

您可以在我撰写的以下文章中阅读有关Kotlin范围函数的内容。它还提到了成员扩展函数的用例:member extension function