'How do I create a button in kotlin without xml?
How do I make a button without any XML? I tried XML but it did not work and it is "Old" I heard.
Solution 1:[1]
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)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Some random IT boy |