android - 是否可以在 Kotlin Anko 中重用布局

标签 android android-layout kotlin anko

我读到使用 Anko 的最大好处是它的可重用性。但我找不到它的确切例子。

目前在新的Android布局系统中,样板如下:

DrawerLayout (with some setup)
   CoordinatorLayout (with some setup)
      AppBarLayout (with some setup)
         ToolBar
      <The Main Content>
   NavigationView (with header inflated)

从上面的布局结构来看,只有<The Main Content>是变化的。和 在许多情况下,这些仪式设置几乎在每项 Activity 中都重复。

所以我在这里与 Anko 一起思考是否有关于该问题的可重用解决方案。我不希望它可重复用于通用布局,但至少我可以最小化项目中的仪式代码。也许我需要类似的东西:

class MainUI: AnkoComponent<MainActivity> {
  override fun createView(ui: AnkoContext<MainActivity>): View{
     return with(ui) {
        myCustomRootLayout {
           //here is what <The Main Content> will be
        }
     }
  }
}

从上面的代码我期待 myCustomRootLayout将为根布局进行所有仪式设置,例如(DrawerLayout、CoordinatorLayout 等)。

这可能吗?

编辑 所以我认为我的问题是:如何制作可以托管其他组件的自定义组件

最佳答案

重用代码的一种方法是简单地将 myCustomRootLayout 提取到扩展方法中,如下所示:

class MainUI: AnkoComponent<MainActivity> {
    override fun createView(ui: AnkoContext<MainActivity>): View {
        return with(ui) {
            myCustomRootLayout {
               recyclerView()
            }
        }
    }
}

fun <T> AnkoContext<T>.myCustomRootLayout(customize: AnkoContext<T>.() -> Unit = {}): View {
    return relativeLayout {
        button("Hello")
        textView("myFriend")
        customize()
    }
}

但是作为 stated in the documentation :

Although you can use the DSL directly (in onCreate() or everywhere else), without creating any extra classes, it is often convenient to have UI in the separate class. If you use the provided AnkoComponent interface, you also you get a DSL layout preview feature for free.

将可重复使用的部分提取到单独的 AnkoComponent 中似乎是个好主意:

class MainUI : AnkoComponent<MainActivity> {
    override fun createView(ui: AnkoContext<MainActivity>): View {
        return with(ui) {
            MyCustomRootLayout<MainActivity>({
                recyclerView()
            }).createView(ui)
        }
    }
}


class MyCustomRootLayout<T : Context>(val customize: AnkoContext<T>.() -> Unit = {}) : AnkoComponent<T> {
    override fun createView(ui: AnkoContext<T>) = with(ui) {
        relativeLayout {
            button("Hello")
            textView("myFriend")
            customize()
        }
    }
}

关于android - 是否可以在 Kotlin Anko 中重用布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40076956/

相关文章:

android - 如何避免 `Activity pause timeout for ActivityRecord` 错误?

android - 如何编程图形界面是盲的?

class - Kotlin 为枚举类值方法定义接口(interface)

kotlin - "withContext"会创建一个新的协程吗?

kotlin - 在 IntelliJ IDEA 项目中使用 kotlinx.coroutines

android - 在 ViewModel 中加载已在 SplashActvity 中检索到的数据

android - 如果 adb logcat 上的条件不起作用

android - 如何获取Android设备的默认字体?

android - 使用加载 gif 将项目动态添加到 NavigationView

android - 在支持多密度的屏幕上设置多个图像