Skip to content

Instantly share code, notes, and snippets.

@hoangchungk53qx1
Created November 28, 2023 10:37
Show Gist options
  • Save hoangchungk53qx1/c75dbc2454ebbc2887a51c9b592d14ad to your computer and use it in GitHub Desktop.
Save hoangchungk53qx1/c75dbc2454ebbc2887a51c9b592d14ad to your computer and use it in GitHub Desktop.
FocusRequesterRestore
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import com.example.outlinedtextfieldtest.ui.theme.OutlinedTextFieldTestTheme
class MainActivity : ComponentActivity() {
private var content: Content = Content("Initial text")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Screen(content) {
content = it
}
}
}
}
@Composable
private fun Screen(content: Content, onTextChanged: (Content) -> Unit) {
OutlinedTextFieldTestTheme {
val focusRequester = remember { FocusRequester() }
var localText by rememberSaveable(content, stateSaver = TextFieldValue.Saver) {
mutableStateOf(
TextFieldValue(
text = content.text,
selection = TextRange(content.text.length)
)
)
}
OutlinedTextField(
modifier = Modifier.focusRequester(focusRequester),
value = localText,
onValueChange = {
localText = it
onTextChanged(Content(it.text))
},
)
LaunchedEffect(focusRequester) {
focusRequester.requestFocus()
}
}
}
data class Content(val text: String)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment