Remove focus from TextField in Android (parity with iOS)

android

#1

Anyone doesn’t like to keep your TextField focused / want to remove focus from your TextField (not just hide the keyboard), here you go.

A custom component for Android that wraps focusable linear layout.

import { View } from 'ui/core/view';

declare var android;

export class AutoFocusView extends View {
    createNativeView() {
        const linearLayout = new android.widget.LinearLayout(this._context);
        linearLayout.setFocusableInTouchMode(true);
        linearLayout.setFocusable(true);
        return linearLayout;
    }

    onLoaded() {
        super.onLoaded();
        this.requestFocus();
    }

    requestFocus() {
        const nativeViewProtected = this.nativeViewProtected;
        nativeViewProtected.requestFocus();
    }
}

XML

<Page loaded="pageLoaded" class="page" xmlns:comp="components/auto-focus-view" xmlns="http://www.nativescript.org/tns.xsd">

	<ActionBar title="Home" class="action-bar">
	</ActionBar>

	<ScrollView>
		<StackLayout class="m-15 form">
			<android>
				<comp:AutoFocusView id="autoFocusView"></comp:AutoFocusView>
			</android>
			<TextField hint="Email address" class="input input-border"></TextField>
			<TextField hint="Password" class="m-t-10 input input-border"></TextField>
			<Button text="Remove focus" class="btn btn-primary" tap="onTapLogin"></Button>
		</StackLayout>
	</ScrollView>
</Page>

TS

import { isAndroid } from 'platform';
import { AutoFocusView } from '../components/auto-focus-view'

export function onTapLogin(args: EventData) {
    if (isAndroid) {
        (<AutoFocusView>topmost().currentPage
            .getViewById("autoFocusView"))
            .requestFocus();
    }
}

If there is an easier / better solution, feel free to comment.


Problem with hiding keyboard from search bar on page load
#2

I was working on this same issue last night. Tried lots of stuff, but this seems to do the trick:

// Dismiss Android keboard on startup
exports.onNavigatedTo = function (args) {
  var page = args.object;
  var textfield = page.getViewById('firstname');
  textfield.focus();
  textfield.dismissSoftInput();
}

Then, in the xml file, simply add navigatedTo=“onNavigatedTo” to the tag.


#3

I have an easier solution for that,

create a TextField like this
<TextField height="0" id="dummy"></TextField>

and just focus on that and dismiss keyboard, when user taps outside textfield :slight_smile:


#4

That’s a nice little hack but just have to make sure it doesn’t mess with accessibility and Samsung devices (most problematic devices :smile: )


#5

there won’t be any problem with accessibility either, cus it doesn’t even display on the screen,
since the height is zero. you can safely keep it outside the form content.


#6

There is a specific option in Accessibility mode which reads from top to bottom - each element one after another. I recall facing such issues on hidden / size zero elements, but of course it’s a quick little hack.