I have a screen with several focusable widgets for TV.
Every time I have to click the direction key then Box01
get focused.
Does anyone know how to set Box01
focused by default?
My Code:
@Composable
fun DefaultFocusSample(){
Row(Modifier.padding(100.dp)) {
FocusBox("Box01")
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box02")
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box03")
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box04")
}
}
@Composable
fun FocusBox(text:String){
var color by remember { mutableStateOf(White) }
Box(
Modifier
.onFocusChanged {
color = if (it.isFocused) Green else White }
.focusable()
.border(2.dp,color)
){
Text(text = text,
modifier = Modifier.padding(10.dp))
}
}
Recomposition is when Jetpack Compose re-executes the composables that may have changed in response to state changes, and then updates the Composition to reflect any changes. A Composition can only be produced by an initial composition and updated by recomposition.
Jetpack Compose is Android's modern toolkit for building native UI. It simplifies and accelerates UI development on Android bringing your apps to life with less code, powerful tools, and intuitive Kotlin APIs. It makes building Android UI faster and easier.
Jetpack Compose is Android's newest toolkit for building UI natively. If you have developed applications in the past, you might be familiar with these two options when creating a layout: Creating an XML file. Building the UI inside of your class by code.
To manually bring focus to focusable, you can use FocusRequester
, like this:
@Composable
fun FocusBox(text:String, requester: FocusRequester = FocusRequester()){
var color by remember { mutableStateOf(Color.White) }
Box(
Modifier
.focusRequester(requester)
.onFocusChanged {
color = if (it.isFocused) Color.Green else Color.White
}
.focusable()
.border(2.dp, color)
) {
Text(text = text,
modifier = Modifier.padding(10.dp))
}
}
Row(
Modifier
.background(Color.Yellow)
.padding(10.dp)
) {
val requester = FocusRequester()
FocusBox("Box01", requester)
LaunchedEffect(Unit) {
requester.requestFocus()
}
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box02")
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box03")
Spacer(modifier = Modifier.padding(10.dp))
FocusBox("Box04")
}
LaunchedEffect
is a side effect, it'll be run only once when composable appears. Check out more in the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With