【问题标题】:Anko view from class课堂上的 Anko 视图
【发布时间】:2017-02-24 15:18:23
【问题描述】:

我已经实现了一个执行各种 api-request 的类,我的想法是该类的每个实例都有一个方法来创建一个视图以具有类似平铺的界面。

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

使用 Anko 和 Kotlin 的首选方式是什么?

【问题讨论】:

    标签: android kotlin anko


    【解决方案1】:

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

    假设CustomView 是您的自定义View 类名,并且 customView 是你想在 DSL 中写的。

    如果您只打算在 DSL 中使用自定义 View 其他一些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)
    

    所以现在你可以这样写:

    frameLayout {
        customView()
    }
    

    …或者这个(参见 UI 包装器章节):

    UI {
        customView()
    }
    

    但是,如果您想将视图用作没有 UI 的顶级小部件 Activity 中的包装器,也添加这个:

    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()
                }
            }
        }
    }
    

    【讨论】:

    • 我已经阅读了这部分文档,但对我来说仍然不清楚如何使用这个代码 sn-ps。你有例子吗?
    • @aul12 添加了一个例子
    • 嗯,该文档的链接已失效。似乎 Anko 存储库中的 docs 已被三个不是特别有用的 png 图像取代......
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多