DEV Community

ShoheOhtani
ShoheOhtani

Posted on

[Kotlin] How to create CustomView reusable

1. RightClick > UiComponent > Custom View
There will be 3 new files created CustomView.kt, view_custom.xml, attrs_custom_view.xml(You can delete if you want).

2. Edit view_custom.xml
Delete views no need and convert Layout to LinearLayout (vertical or horizontal)
Image description

3. Edit CustomView.kt

class CustomView: LinearLayout {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)

    init {
        LayoutInflater.from(context).inflate(R.layout.view_custom, this)
    }
}
Enter fullscreen mode Exit fullscreen mode

If you want to get object on layout.

private val someTextView: TextView by lazy { findViewById(R.id.some_text_view) }
Enter fullscreen mode Exit fullscreen mode

Discussion (0)