How to clear focus of BasicTextField upon clicking somewhere else in Compose Multiplatform? - kotlin

I have a BasicTextField in Jetbrains Compose Multiplatform for desktop. When I click on it, the TextField gets focus and becomes editable. However, when I click somewhere else in my application, the focus is not lost and the field is still editable as if I just clicked on it.
I know this behavior is normal and intended. Nonetheless, I want to the TextField to become unfocused when the user clicks somewhere else, regardless of it being a clickable or non-clickable composable.
How do I achieve this?

This is one way I've done it in the past.
val keyboardController = LocalSoftwareKeyboardController.current
val focusManager = LocalFocusManager.current
val interactionSource = remember { MutableInteractionSource() }
Then I made my parent layout clickable.
Box(modifier = Modifier
.clickable(
interactionSource = interactionSource,
indication = null // this gets rid of the ripple effect
) {
keyboardController?.hide()
focusManager.clearFocus(true)
}

Related

Jetpack compose: Top App Bar pinnedScrollBehavior not changing color on scroll from text focus events

Okay, so this is a bit of a specific issue, but hopefully someone understands what's happening:
I'm using a Jetpack Compose Material 3 CenterAlignedTopAppBar, with TopAppBarDefaults.pinnedScrollBehavior to make it so that the color of the appbar changes when I scroll down on nested content.
It works! In most cases. However, one of my screens has a large text field, that when clicked causes the content to scroll down by itself (to focus on the text field)—and that seems to confuse the appbar, which doesn't change color. It will only change color if I manually scroll up and down.
Relevant code:
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
Scaffold(
contentWindowInsets = EmptyWindowInsets,
modifier = Modifier
.fillMaxHeight()
.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = {
// just a wrapper around CenterAlignTopAppBar
StandardTopAppBar(scrollBehavior = scrollBehavior)
},
content = { innerPadding ->
// I've also tried with LazyColumn and see the same behavior
Column(
Modifier
.padding(innerPadding)
.padding(start = 10.dp, end = 10.dp)
.fillMaxHeight()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
tl;dr; manually scrolling changes the appbar color, but scrolling caused by clicking into a text field that scrolls into view does not. Any idea how I could fix this?
Probably not quite what you are looking for unfortunately, but I had a similar problem. My TopAppBar color was also stuck, but when navigating between different screens. I fixed it by assigning the TopAppBar a different scrollBehaviour depending on the screen.
val scrollBehavior1 = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
val scrollBehavior2 = TopAppBarDefaults.pinnedScrollBehavior(rememberTopAppBarState())
In TopAppBar arguments:
scrollBehavior =
when (currentRoute) {
Screens.ExampleScreen1.route -> scrollBehavior1
Screens.ExampleScreen2.route -> scrollBehavior2
else -> null
}
Hopefully this helps you in one way or another.

Jetpack Compose - ModalBottomSheet comes up with soft keyboard

I have a problem with ModalBottomSheet and it's on my work computer so I can't record it to you right now. So basically, after I give focus to one of my TextFields, my keyboard comes up and pushes all the content upwards so I can see the TextField that I'm writing to. When I'm hiding my keyboard I can see that my ModalBottomSheet hides too, but I never set it to come up.
So if you are familiar with this bug, please let me know your solutions.
My coworker, so he inserted a boolean that checks if keyboard is up or not and if it is, dont put ap modal bottom sheet.
You can use this method until this problem is fixed with an additional update.
You can use LaunchedEffect for this. Here is an example for you.
The important thing here is to disable the ModalBottomSheetDialog when the keyboard is opened and re-enable it half a second after the keyboard is closed.
You can trigger the required function by assigning a value to this variable when the keyboard is turned on, and then changing and checking this value when the keyboard is closed.
/*Change this value to "keyboard_on" when the keyboard is turned on and "keyboard_off" when the keyboard is closed again. You can give different names for different usage areas. That's why we're using a string, not a Boolean.*/
var taskCodeValue = remember { mutableStateOf("keyboard_off") }
var sheetOpener by remember { mutableStateOf(true) }
if (taskCodeValue.value == "keyboard_off"){
LaunchedEffect(taskCodeValue.value == "keyboard_off"){
delay(500)
sheetOpener = true
}
}else {
sheetOpener = false
}
/*
By adding the Scaffold, which includes ModalBottomSheet and other compose
elements, into a box, we enable them to work independently of each other.
*/
Box(modifier = Modifier.fillMaxSize()) {
Scaffold(
content = {}
)
if (sheetOpener){
ModalBottomSheetLayout(
sheetState = sheetState,
sheetContent = {}
) {}
}
}

Why scrollable modifier doesn't scroll view content?

I am trying to get scrolling to work on a Column where the number of entries may exceed the height of the window.
I'm currently using Compose 1.1.0-rc03 and at the moment I'm only trying to get it working on desktop.
I reduced the problem to this:
#Composable
fun App() {
val optionsScrollState = rememberScrollState()
Row(modifier = Modifier.fillMaxSize()) {
// Left column
Column(
modifier = Modifier
.scrollable(optionsScrollState, Orientation.Vertical)
.width(240.dp)
.fillMaxHeight()
) {
(1..100).forEach { i -> Text("Row $i") }
}
}
}
But this doesn't scroll, or at least, not with the mousewheel. Maybe there's another way to scroll that isn't immediately apparent to me.
How do I make this work?
The docs on scrollable say that I might have to manage the state myself. So is using rememberScrollState() not enough?
I found some existing questions about disabling scrolling on columns, but they were always talking about LazyColumn which I'm not using here.
You're using a wrong modifier. From documentation:
The scrollable modifier differs from the scroll modifiers in that scrollable detects the scroll gestures, but does not offset its contents.
If you're interested how Modifier.scrollable should be used, you can find an example in the same documentation chapter.
You can use Modifier.verticalScroll instead, which will give you the expected behavior.
Also consider switching to LazyColumn, which already has built-in scrolling as well as lazy cell loading.

TextField Covered By Software Keyboard And Doesn't Scroll Into View

When using Compose with a TextField at the bottom of the screen, when I focus the TextField, the software keyboard is opening up and covering the TextField, and it is not scrolling the TextField into view.
I am using accompanist and have things set up so that it could scroll into view, but it is not doing it automatically.
I also found that if the keyboard is already open, and you focus a TextField that is scrolled off screen, it does automatically scroll it onto screen. So it sort of seems like the behavior is there, but it just isn't working correctly because the focus happens before the keyboard opens.
Does anyone have a good solution to make the TextField scroll into view when the software keyboard opens?
Edit:
Simple Example:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
setContent {
ProvideWindowInsets {
Column(
Modifier
.statusBarsPadding()
.navigationBarsWithImePadding()
.verticalScroll(rememberScrollState())
) {
val focusManager = LocalFocusManager.current
(0..20).forEach {
var test by remember { mutableStateOf("") }
TextField(
test,
{ test = it },
label = { Text(it.toString()) },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
keyboardActions = KeyboardActions(onNext = {
focusManager.moveFocus(FocusDirection.Next)
})
)
}
}
}
}
}
}
With the keyboard closed, if I click a TextField near the bottom, it gets focus, then the keyboard pops up and covers it. What I want to happen is after the keyboard pops up, the TextField should scroll into view.
However if I then hit the Next button on the keyboard, it will go to the next TextField and scroll it into view. Which is what I want.
I had a similiar issue. This seems to be a bug in Compose. To fix it, add the following in your activity's onCreate:
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)

Clickable box makes its "non-clickable parent box" clickable as well?

Here is the code snippet:
Box(
Modifier
.size(48.dp, 48.dp)
.background(Color.Transparent)
.align(Alignment.CenterEnd)
)
{
Box(
Modifier
.size(height = 35.636363.dp, width = 41.818181.dp)
.align(Alignment.CenterEnd)
.clip(RoundedCornerShape(topStart = 20.dp, bottomStart = 20.dp))
.clickable(onClick = {showDialogFragment.value = true})
.background(Color.Red)
)
}
Whenever i click on parent box (the one which is transparent) it activates click event of its only child. Why so? Current behavior meets my needs, but i dont understand why it happens.
According to Material Guidelines, the minimum touch size is 48.dp.
Since 1.1.0-alpha03, when you add touch detection to a view with a size smaller than this value, tracking will work on the enlarged frame.
Added minimum touch target size to ViewConfiguration for use in semantics and pointer input to ensure accessibility.
Just out of curiosity, you can check the extended touch padding for the current view using pointerInput modifier, which lies under all touch processing in Compose:
.pointerInput(Unit) {
println("$extendedTouchPadding")
}