Yes! You absolutely can! In fact, creating views and UI programmatically has a lot of great benefits in Android:
- Since you're not inflating and using XML files, rendering performance becomes a lot faster and more performant, especially for more complicated UI.
- Your views and UI can now be a lot more flexible and reusable, especially when you need to change UI dynamically at runtime.
- You can store a lot of binding and manipulation logic right into a custom view class, so you can do things like
myCustomView.updateLabel("new label")
without having to do stuff like findViewById(...)
- You can encapsulate your programmatic UI into reusable classes, like the one shown below:
class MyCustomView : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context, attrs, defStyleAttr
)
init {
val button = Button(context)
val buttonParams = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
buttonParams.gravity = Gravity.CENTER
button.text = "Click Me!"
button.layoutParams = buttonParams
this.addView(button)
}
}
This class creates a FrameLayout that has a button with some text on it, centered vertically and horizontally within the FrameLayout.
Although programmatic UI is incredible, you should really use the tool that works best for your use case. If you're creating a UI that will be used in many places in your app, consider doing this programmatically via a custom View class, like the one shown above. If you're just making a one-off UI that is relatively simple and doesn't have a lot of nested layouts, then XML is far quicker and easier.