DEV Community

ShoheOhtani
ShoheOhtani

Posted on

1 1

[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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay