gpt4 book ai didi

android - 类里面的Anko视角

转载 作者:搜寻专家 更新时间:2023-11-01 07:46:48 24 4
gpt4 key购买 nike

我已经实现了一个执行各种 api 请求的类,我的想法是该类的每个实例都有一个方法来创建一个 View ,使其具有类似 tile 的界面。

我的问题是我不知道应该如何以好的方式实现。

使用 Anko 和 Kotlin 执行此操作的首选方法是什么?

最佳答案

Anko 很棒documentation about that case (但是谁会阅读文档,是吗?)

Let's say, CustomView is your custom View class name, and customView is what you want to write in the DSL.

If you only plan to use your custom View in the DSL surrounded by some other View:

inline fun ViewManager.customView(theme: Int = 0) = customView(theme) {}
inline fun ViewManager.customView(theme: Int = 0, init: CustomView.() -> Unit) = ankoView({ CustomView(it) }, theme, init)

So now you can write this:

frameLayout {
customView()
}

…or this (see the UI wrapper chapter):

UI {
customView()
}

But if you want to use your view as a top-level widget without a UI wrapper inside Activity, add this as well:

inline fun Activity.customView(theme: Int = 0) = customView(theme) {}
inline fun Activity.customView(theme: Int = 0, init: CustomView.() -> Unit) = ankoView({ CustomView(it) }, theme, init)

示例(这就是我的使用方式,您可以选择不同的方法):

class YourAwesomeButton: Button() {
/* ... */
fun makeThisButtonAwesome() {/* ... */}
}

/** This lines may be in any file of the project, but better to put them right under the button class */
inline fun ViewManager.yourAwesomeButton(theme: Int = 0) = yourAwesomeButton(theme) {}
inline fun ViewManager.yourAwesomeButton(theme: Int = 0, init: CustomView.() -> Unit) =
ankoView({ YourAwesomeButton(it) }, theme, init)

在另一个文件中:

class YourAwesomeActivity: Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(saveInstanceState)
relativeLayout(R.style.YourAwesomeAppTheme) {
yourAwesomeButton(R.style.YourAwesomeAppTheme) {
makeThisButtonAwesome()
}.lparams {
centerInParent()
}
}
}
}

关于android - 类里面的Anko视角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42442165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com