Reputation: 1
How do I make a button without any XML? I tried XML but it did not work and it is "Old" I heard.
Upvotes: 0
Views: 946
Reputation: 8467
Yeah, using XML is old but it's the standard way of defining views in Android. Nowadays exist alternatives to that such as Jetpack Compose which takes a more React
style when declaring the GUI where you write @Composable
functions that produce a UI. Quite nice.
In any case you can create the views yourself programatically but it's much more tedious, less maintainable and imho 💩
With that said, from your activity you can create instances of any of the layouts that you would use in XML and then add more views into it:
class YourActivty: AppCompatActivity() {
override fun onCreate(...) {
val frameLayout = FrameLayout(this).apply {
// Configure the layout's properties
}
val button = AppCompatButton(this).apply {
// Configure all button's properties
}
frameLayout.addView(button)
// Indicate your activity to use the framelayout as its content
setContentView(frameLayout)
}
}
Upvotes: 1