This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Keyboard handling in Jetpack Compose


Getting into information is a crucial job in lots of apps. On gadgets with no bodily keyboard (the overwhelming majority in Android land) a so-called smooth(ware) keyboard handles person enter. Now, you might be questioning why we have to discuss these digital peripherals in any respect. Should not the working system take care? I imply, when it comes to person interface, the app expresses its need to permit person enter by displaying and configuring an editable textual content subject. What else must be executed? This text takes a better have a look at how Jetpack Compose apps work together with the keyboard.

Let’s begin with a easy Compose hierarchy:

@Composable
enjoyable KeyboardHandlingDemo1() {
  var textual content by bear in mind { mutableStateOf(TextFieldValue()) }
  Column(
    modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Association.Backside
  ) {
    Field(
      modifier = Modifier
        .padding(16.dp)
        .fillMaxSize()
        .background(shade = MaterialTheme.colours.main)
        .weight(1.0F),
      contentAlignment = Alignment.BottomCenter
    ) {
      Textual content(
        modifier = Modifier.padding(backside = 16.dp),
        textual content = stringResource(id = R.string.app_name),
        shade = MaterialTheme.colours.onPrimary,
        type = MaterialTheme.typography.h5
      )
    }
    TextField(modifier = Modifier.padding(backside = 16.dp),
      worth = textual content,
      onValueChange = {
        textual content = it
      })
  }
}
Enter fullscreen mode

Exit fullscreen mode

Screenshot of KeyboardHandlingDemo1()

Appears to be like good, proper? Now, let’s examine what occurs if the textual content subject will get focus.

KeyboardHandlingDemo1() with a visible soft keyboard

This absolutely would not look horrible, however it is not nice, both. Because the textual content subject will doubtless have the eye of the person, it needs to be seen absolutely, proper? Right here, it is essential to know how the smooth keyboard interacts with the exercise and the window the exercise is displayed in. There has virtually at all times (since API stage 3) been a manifest attribute for this, windowSoftInputMode. It belongs to <exercise />.

The attribute …

controls how the principle window of the exercise interacts with the window containing the on-screen smooth keyboard.

There are two primary facets:

  • Ought to the smooth keyboard be seen when the exercise turns into the main target of person consideration?
  • Which adjustment needs to be made to the exercise’s primary window when part of the window is roofed by the smooth keyboard?

On this article, I am going to give attention to the latter one. For a basic introduction, please consult with Handle input method visibility.

Now, let us take a look at adjustment-related values.

adjustUnspecified is the default setting for the conduct of the principle window. The doc says:

It’s unspecified whether or not the exercise’s primary window resizes to make room for the smooth keyboard, or whether or not the contents of the window pan to make the present focus seen on-screen. The system will mechanically choose one in every of these modes relying on whether or not the content material of the window has any format views that may scroll their contents. If there may be such a view, the window can be resized, on the belief that scrolling could make the entire window’s contents seen inside a smaller space.

adjustResize:

The exercise’s primary window is at all times resized to make room for the smooth keyboard on display.

adjustPan:

The exercise’s primary window shouldn’t be resized to make room for the smooth keyboard. Moderately, the contents of the window are mechanically panned in order that the present focus is rarely obscured by the keyboard and customers can at all times see what they’re typing. That is usually much less fascinating than resizing, as a result of the person may have to shut the smooth keyboard to get at and work together with obscured components of the window.

In the event you recall the final screenshot, the window clearly is not resized. So, …

The system will mechanically choose one in every of these modes relying on whether or not the content material of the window has any format views that may scroll their contents.

… appears to not work effectively for Compose apps. Which is actually not stunning, as the basis view of a Compose hierarchy being displayed utilizing setContent { ... } is ComposeView, which extends AbstractComposeView, which in flip extends ViewGroup (which might’t scroll).

So, the repair is straightforward: simply add

android:windowSoftInputMode="adjustResize"
Enter fullscreen mode

Exit fullscreen mode

to your <exercise /> tag.

KeyboardHandlingDemo1() in a properly resized window



A number of textual content fields

Let’s take a look at one other Compose hierarchy:

@Composable
enjoyable KeyboardHandlingDemo2() {
  val states = bear in mind {
    mutableStateListOf("1", "2", "3", 
        "4", "5", "6", "7", "8", "9", "10")
  }
  val listState = rememberLazyListState()
  LazyColumn(
    state = listState,
    modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally
  ) {
    itemsIndexed(states) { i, _ ->
      OutlinedTextField(worth = states[i],
        modifier = Modifier.padding(high = 16.dp),
        onValueChange = {
          states[i] = it
        },
        label = {
          Textual content("Textual content subject ${i + 1}")
        })
    }
  }
}
Enter fullscreen mode

Exit fullscreen mode

KeyboardHandlingDemo2() with open soft keyboard

The person interface accommodates fairly just a few editable textual content fields. Nevertheless, with the above implementation, the person can’t transfer to the following subject utilizing the smooth keyboard, however should click on and scroll. Thankfully, we are able to obtain this simply utilizing Compose keyboard actions and choices. The next strains are added to the decision to OutlinedTextField():

keyboardOptions = KeyboardOptions(imeAction = ImeAction.Subsequent),
keyboardActions = KeyboardActions(
  onNext = {
    focusManager.moveFocus(FocusDirection.Down)
  }
),
Enter fullscreen mode

Exit fullscreen mode

We configure the smooth keyboard to show a particular Subsequent key (ImeAction.Subsequent) and use a FocusManager (which belongs to package deal androidx.compose.ui.focus) contained in the onNext callback of KeyboardActions to navigate (transfer the main target) to the (vertically) subsequent textual content subject.

val focusManager = LocalFocusManager.present
Enter fullscreen mode

Exit fullscreen mode

Cool, proper? There may be yet another factor we have to do, although. Our textual content fields belong to a scrollable listing. Shifting focus doesn’t change the portion of the listing that’s at present seen. This is how to try this:

listState.animateScrollToItem(i)
Enter fullscreen mode

Exit fullscreen mode

animateScrollToItem() is a droop operate, so it needs to be known as from a coroutine or one other droop operate.

coroutineScope.launch {
  listState.animateScrollToItem(i)
}
Enter fullscreen mode

Exit fullscreen mode

Lastly, to get a coroutine scope in a composable operate, you need to use rememberCoroutineScope():

val coroutineScope = rememberCoroutineScope()
Enter fullscreen mode

Exit fullscreen mode

There’s yet another factor I might like to point out you: the best way to shut the software program keyboard.



Exhibiting and hiding the smooth keyboard

The next screenshot reveals my KeyboardHandlingDemo3() composable operate. It permits the person to enter a quantity and computes its sq. after the Calculate button or the particular Completed key on the smooth keyboard was pressed. What you may’t see on the screenshot: the smooth keyboard is closed. This can be fascinating to once more present the whole person interface after the information has been enter.

The KeyboardHandlingDemo3() example

Let’s take a look at the code:

@ExperimentalComposeUiApi
@Composable
enjoyable KeyboardHandlingDemo3() {
  val kc = LocalSoftwareKeyboardController.present
  var textual content by bear in mind { mutableStateOf("") }
  var end result by bear in mind { mutableStateOf("") }
  val callback = {
    end result = attempt {
      val num = textual content.toFloat()
      num.pow(2.0F).toString()
    } catch (ex: NumberFormatException) {
      ""
    }
    kc?.cover()
  }
  Column(
    modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Association.Middle
  ) {
    Row {
      TextField(modifier = Modifier
        .padding(backside = 16.dp)
        .alignByBaseline(),
        keyboardOptions = KeyboardOptions(
          keyboardType = KeyboardType.Quantity,
          imeAction = ImeAction.Completed
        ),
        keyboardActions = KeyboardActions(
          onDone = {
            callback()
          }
        ),
        worth = textual content,
        onValueChange = {
          textual content = it
        })
      Button(modifier = Modifier
        .padding(begin = 8.dp)
        .alignByBaseline(),
        onClick = {
          callback()
        }) {
        Textual content(stringResource(id = R.string.calc))
      }
    }
    Textual content(
      textual content = end result,
      type = MaterialTheme.typography.h4
    )
  }
}
Enter fullscreen mode

Exit fullscreen mode

The computation takes place within the callback lambda. Right here, the smooth keyboard is closed, too, by invoking cover() on a LocalSoftwareKeyboardController occasion. Please notice that this API is experimental and will change in future Compose variations.

We configure a quantity pad with a Completed key by passing keyboardType = KeyboardType.Quantity and imeAction = ImeAction.Completed to KeyboardOptions(). The callback lambda is invoked from the onClick callback of the button and inside onDone, which belongs to KeyboardActions().



Conclusion

On this article I confirmed you the best way to work together with the smooth keyboard in Compose apps. Did I miss one thing? Would you want a comply with up? Kindly share your ideas within the feedback.


Source

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?