Tuesday, 20 August 2013

Play with Android Keyboard (Updated with androidx package)

In this tutorial, we will understand various interesting things related to Android's keyboard.


1) Show or Hide keyboard:
When you create an app which expects some input from the user through the EditText, every time the user has to click on the EditText in order to get the keyboard. But it is possible to show or hide the keyboard at any time.

You can see from the above screen shots, the keyboard can be shown even if there is no EditText.

This code is used to show the keyboard at start of the Activity. Comment the line of ...STATE_VISIBLE and uncomment the line of ...STATE_HIDDEN to hide the keyboard at any time.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;

public class HideKeyboardActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hide_keyboard_activity);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
}

2) Allow only Numbers as input (Not even decimals) :
You cannot write any text except numbers when you add 'inputType=number' in the xml layout file's EditText.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HideKeyboardActivity"
android:background="#ffea00"
android:gravity="">

<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:textSize="20sp"
android:inputType="number"
android:hint="Only numbers are allowed here..."
android:background="#ffffff"/>
</LinearLayout>

3) Allow numbers and decimals:


<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:textSize="20sp"
android:inputType="numberDecimal"
android:hint="Numbers and decimals are allowed here..."
android:background="#ffffff"/>

4) Allow phone number:


<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:textSize="20sp"
android:inputType="phone"
android:hint="Phone numbers are allowed here..."
android:background="#ffffff"/>
5) Allow only number password:


<EditText
android:layout_width="match_parent"
android:layout_height="80dp"
android:gravity="center"
android:textSize="20sp"
android:inputType="numberPassword"
android:hint="Only number passwords are allowed here..."
android:background="#ffffff"/>
In similar way there are options for multi line edit, text password, data, time and a lot of other.

No comments:

Post a Comment