Correct way to dismiss keyboard from a TextView in Nativescript

Dailyrox picture Dailyrox · Oct 26, 2016 · Viewed 9k times · Source

I have the following TextView:

<TextView id="textFieldBody" hint="Some hint" text="{{  }}" editable="true" class="TextField" returnKeyType="done" />

I'm trying to correctly implement it so that:

  • when the user presses "Done", the keyboard disappears
  • when the user touches outside (blur) of the TextView, the keyboard disappears
  • maybe when focus on the TextView, scroll up so that the rest of the view doesn't disappear behind the keyboard? (not sure yet about this one)

It's unclear to me how to achieve that. What kind of backend code do I need to implement?

Ideally, I'm looking for a solution that works for both iOS and Android.

Answer

Dean Le picture Dean Le · Oct 26, 2016

When the user press done, keyboard disappears

For this one, you can put a listener to the textview so that it will get triggered when user press the done button. As I had a look at NativeScript API, this listener is only applied for TextField, but you can give TextView a try:

In XML:

<TextField returnPress="doneTap"/>

In .js file:

function doneTap(args) {
    var myTextField = args.object;
    myTextField.dismissSoftInput();
}
exports.doneTap = doneTap

When the user touches outside (blur) of the TextView, the keyboard disappears

For this one, you will put a listener to the parent view of the TextField. When you tap outside, it will invoke the function to hide the keyboard. The good thing is that this listener will be overrided by TextField tap. So when you tap on the TextField, the keyboard still shows up. You can find the answer here

When focus on the TextView, scroll up so that the rest of the view doesn't disappear behind the keyboard?

Using this plugin to prevent keyboard from covering the textfield