Middle
How to implement a user interface in Android without using XML?
sobes.tech AI
Answer from AI
We can use Kotlin/Java code for programmatically creating and adding Views and ViewGroups.
Example of creating a TextView:
// Creating TextView in code
val textView = TextView(context)
// Setting properties
textView.text = "Hello, world!"
textView.textSize = 20f
textView.setTextColor(Color.BLACK)
textView.gravity = Gravity.CENTER
// Adding TextView to a ViewGroup (e.g., LinearLayout)
val linearLayout = LinearLayout(context)
linearLayout.orientation = LinearLayout.VERTICAL
linearLayout.addView(textView)
// Setting the root layout
setContentView(linearLayout)
For more complex interfaces, "programmatic" layout creation involves combining various ViewGroup and View elements.
Advantages:
- Dynamic UI creation based on data or logic.
- More fine-grained control over component creation.
- Potentially slightly faster, as there is no XML parsing.
Disadvantages:
- Code becomes less readable and more cumbersome for complex layouts.
- Difficult to visualize the layout without running the app.
- Lack of convenient preview tools like in XML.
Modern approaches, such as Jetpack Compose (which uses Kotlin), describe UI entirely declaratively in code, replacing XML.
Here's an example in Jetpack Compose:
// In a @Composable function, define the UI
@Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}
// Use this function in an Activity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Greeting("World")
}
}
}