Create a custom View/ViewGroup class in Anko DSL
Asked Answered
P

2

12

I want to create a custom View which is just a wrapper of some Android Views. I looked into creating a custom ViewGroup which manages the layout of it's child views, but I don't need such complexity. What I basically want to do is something like:

class MainActivity
verticalLayout {
  textView {
    text = "Something that comes above the swipe"
  }
  swipeLayout {
  }
}

class SwipeLayout
linearLayout {
  textView {
    text = "Some text"
  }
  textView {
    text = "Another text"
  }
}

The reason is that I'd like to move the SwipeLayout code into a separate file but don't want to do any complex layout stuff myself. Is this possible using Anko?

Edit: As suggested, Is it possible to reuse a layout in Kotlin Anko solves this problem if the view is a root layout. But as shown in the example, I'd like to include this within another layout. Is that possible?

Pleonasm answered 20/10, 2016 at 6:51 Comment(3)
Possible duplicate of Is it possible to reuse a layout in Kotlin AnkoLyceum
I agree with @miensol. Please refer to this answer: https://mcmap.net/q/1011158/-is-it-possible-to-reuse-a-layout-in-kotlin-ankoFrendel
I'm sorry. This should have been okay. But what if I do not want my custom view to be a root layout? Like in the example I have shown, it's included into another layout. When I try to do that, I get a java.lang.IllegalStateException: View is already set: org.jetbrains.anko._LinearLayout{8bdb786 V.E...... ......I. 0,0-0,0}Pleonasm
M
6

you can use ViewManager.

fun ViewManager.swipeLayout() = linearLayout {
  textView {
    text = "Some text"
  }
  textView {
    text = "Another text"
  }
}

class MainActivity
  verticalLayout {
    textView {
      text = "Something that comes above the swipe"
    }
    swipeLayout {}
}
Misreport answered 14/12, 2016 at 2:38 Comment(0)
T
3

I was looking for something like this too, but the most optimal solution i found for custom views is something like this:

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

class CustomLayout(c: Context) : LinearLayout(c) {
    init {
        addView(textView("Some text"))
        addView(textView("Other text"))
    }
}
Tolbert answered 5/12, 2016 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.