EditText with number keypad by default, but allowing alphabetic characters

AndroidAndroid Keypad

Android Problem Overview


I have an EditText box and I want the default keyboard that comes up when it is selected to be the numeric keypad, since most of the time users will be entering numbers. However, I do want to allow users to enter alphabetic characters too, if they need to. Using android:inputType="number" restricts input to numeric digits only. What options do I have?

Android Solutions


Solution 1 - Android

Define your EditText in your xml this way:

<EditText 
    android:id="@+id/txtOppCodigoCliente"
    android:inputType="textVisiblePassword"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:maxLength="11"
    android:hint="@string/strCodigoCliente"/>

output: android:inputType="textVisiblePassword"

A row of numbers and the rest of letters.

Solution 2 - Android

I would suggest a more Robust solution:

Present the user with the ability to choose the input type:

NEEDED FIXES

-better handling of showing/hiding the input selection buttons

-probably remove the suggestions when the input type is letter

enter image description here

Here is the activity:

package mobi.sherif.numberstexttextview;

import android.os.Bundle;
import android.app.Activity;
import android.text.InputType;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;

public class MainActivity extends Activity {

	EditText mEdit;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mEdit = (EditText) findViewById(R.id.input);
		mEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean focused) {
				findViewById(R.id.llmenu).setVisibility(focused?View.VISIBLE:View.GONE);
			}
		});
	}
	
	public void onNumbers(View v) {
		mEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
	}
	
	public void onLetters(View v) {
		mEdit.setInputType(InputType.TYPE_CLASS_TEXT);
	}

}

Here is the activity's xml : activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignWithParentIfMissing="true"
        android:layout_above="@+id/llmenu" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <EditText
                android:id="@+id/input"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="number" >

                <requestFocus />
            </EditText>
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/llmenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#000000"
        android:padding="0dp" >

        <Button
            android:id="@+id/buttonnumbers"
            android:layout_width="0dp"
            android:onClick="onNumbers"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Numbers" />

        <Button
            android:id="@+id/buttonletters"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="onLetters"
            android:text="Letters" />
    </LinearLayout>

</RelativeLayout>

Solution 3 - Android

Here is what you are looking for:

Define your EditText in your xml this way:

<EditText
    android:id="@+id/etTest"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/hint">

</EditText>

And call following in your onCreate():

etTest = (EditText) findViewById(R.id.etTest);
etTest.setRawInputType(InputType.TYPE_CLASS_NUMBER);
// Note the "Raw"

Whenever you click into your EditText now, you can enter digits AND letters! (Digit keyboard is shown first)

Solution 4 - Android

Unfortunately this is not possible, because only one inputType can be set for an EditText. The following will just show alphabatic characters on buttons.

<EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text|number" />

However, what I can suggest you is, set your input type to numeric, and just add a small switchKeyboard button on your form close to the numpad. And set its onClick

editText1.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

so that users can switch to alphabetic characters, too.

Solution 5 - Android

Basically, EditText inputtype is used to set the input type in your EditText.

The possible values for the android:inputtype are:

  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • number
  • numberSigned
  • numberDecimal
  • phone
  • datetime
  • date
  • time

then you can use any value as showing in example:

<EditText android:id="@+id/EditText01"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent"
 android:inputType="number"
 android:text="1212223"/>

Solution 6 - Android

Asus tablet has that feature, they have customized the default keyboard. And the keyboard contains the numbers and alphabets only. I think your requirement solution is too to customize the default keyboard

Solution 7 - Android

You should not use any inputType filter in this case, just add the below line in your EditText Property

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "

Now only these characters will be allowed to enter in the EditText. The complete code of your edittext will be like this:

<EditText
 android:id="@+id/etTest"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:ems="10"
 android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "
 android:hint="@string/hint">

Solution 8 - Android

You can follow Paresh Mayani answer.

And in advice you can use android:inputType="textPhonetic" for the inputType Text and Number based on user selection.

Hope you will got my point.

Solution 9 - Android

In OnCreate in Activity do this:

    t = (EditText) findViewById(R.id.test);
    t.setKeyListener(new KeyListener() {

        @Override
        public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
            return false;
        }

        @Override
        public boolean onKeyOther(View view, Editable text, KeyEvent event) {
            return false;
        }

        @Override
        public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) {
            if (keyCode == 67) { // Handle backspace button =)
                if (text.length() > 0) {
                    t.setText(text.subSequence(0, text.length() - 1));
                    t.setSelection(text.length()-1);
                }
            }
            return false;
        }

        @Override
        public int getInputType() {
            return InputType.TYPE_CLASS_NUMBER;
        }

        @Override
        public void clearMetaKeyState(View view, Editable content, int states) {

        }
    });

In this case you type is number and android will show numeric keyboard, but you can input whatever you want. Also you can override other methods as you wish.

Solution 10 - Android

Here is how I achieved it...

android:inputType="textPhonetic|numberDecimal" android:digits="/0123456789.abcdefghijklmnopqrstuvwxyz"

Only characters specified by digits will be allowed.

Please note that the keyboard shown is that of the dialer, not the typical keyboard. For me, it achieved what I needed to entirely within the XML.

Solution 11 - Android

Programmatically it is possible with little bit of tweak to the usual flow. First you have to set editText as:

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

Then you have to listen for keyevent. On pressing of pound set the InputType again to InputType.TYPE_CLASS_TEXT. This should work as it works for me.

editText.setOnKeyListener(new View.OnKeyListener() 
{
     @Override
     public boolean onKey(View v, int keyCode, KeyEvent event) {
     // TODO Auto-generated method stub
     Log.d("KeyBoard", "Keyboard Test Key Hit");
            						
        switch (keyCode) 
        {
              KeyEvent.KEYCODE_POUND:

              if(editText.setInputType(InputType.TYPE_CLASS_TEXT);
              {    							
                   editText.setInputType(InputType.TYPE_CLASS_TEXT);
                   return true;
              }
         }
     }
}  

Solution 12 - Android

Why not just have a toggle button that either:

  • Sets the input type to allow only numerical values
  • Sets the input type to allow the use of the QWERTY keyboard
  • Or set other input types (if needed)

That way, you can set the numeric keypad to default, then the user can change it by pressing a button.

Solution 13 - Android

This is not possible given current default Android input types across various phones.

There are many possible hacks that work on some keyboards but not on others, like the common method of setting the raw input type that is commonly included in answers:

  • editText.setRawInputType(InputType.TYPE_CLASS_NUMBER)

Best advice I could find is to use the textPostalAddress input type in your XML:

  • android:inputType="textPostalAddress"

Unfortunately this doesn't do what we want it to do yet, but maybe it will in the future. The only advantage of this is that the meta information on your edit box will reflect what you intend.

Solution 14 - Android

You can try setting---

editText.setRawInputType(Configuration.KEYBOARD_QWERTY);

for more description

Solution 15 - Android

In your code for textView, remove the "text" in android:inputType.

It should be,

<EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="number" />

Solution 16 - Android

You can do this programatically:

// Numbers
mEditText.setInputType(InputType.TYPE_CLASS_NUMBER);

// Text
mEditText.setInputType(InputType.TYPE_CLASS_TEXT);

> setInputType(int type) Set the type of the content with a constant as > defined for inputType.

Solution 17 - Android

As Saurav says, the best way is changing between QWERTY Keyboard and Numeric Keyborad with a simple listener:

input.setInputType(InputType.TYPE_CLASS_TEXT);

input.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
                
        switch (keyCode) {
        case 24: // Volumen UP

             input.setInputType(InputType.TYPE_CLASS_NUMBER);
             break;
         case 25: // Volumen DOWN

             input.setInputType(InputType.TYPE_CLASS_TEXT);
             break;
        }
        return true;
    }
});

Solution 18 - Android

I try all the method but not perfect. So I have another idea. Work perfect for all keyboard.

 @Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_reset_password);
    editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);


    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
        if (editText.isFocused()) {
            editText.setInputType(InputType.TYPE_CLASS_TEXT);
        }

    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
        if (editText.getInputType() == InputType.TYPE_CLASS_TEXT) {
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        }
    }
}

Solution 19 - Android

In your xml layout for EditText add this parameter:

android:inputType="number|text"

This will allow the user to enter both text and number and contains the logic in the xml rather than having code in your activity or fragment.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrank BozzoView Question on Stackoverflow
Solution 1 - AndroidDiego SantamariaView Answer on Stackoverflow
Solution 2 - AndroidSherif elKhatibView Answer on Stackoverflow
Solution 3 - AndroidTerelView Answer on Stackoverflow
Solution 4 - AndroidAlpayView Answer on Stackoverflow
Solution 5 - AndroidParesh MayaniView Answer on Stackoverflow
Solution 6 - AndroidShaista NaazView Answer on Stackoverflow
Solution 7 - AndroidNaveed AhmadView Answer on Stackoverflow
Solution 8 - AndroidShreyash MahajanView Answer on Stackoverflow
Solution 9 - AndroiddilixView Answer on Stackoverflow
Solution 10 - AndroidslamanView Answer on Stackoverflow
Solution 11 - AndroidSauravView Answer on Stackoverflow
Solution 12 - AndroiddabaerjuView Answer on Stackoverflow
Solution 13 - AndroidRichard Le MesurierView Answer on Stackoverflow
Solution 14 - AndroidSwatiView Answer on Stackoverflow
Solution 15 - AndroidMs. BView Answer on Stackoverflow
Solution 16 - Androidjmcdonnell40View Answer on Stackoverflow
Solution 17 - AndroidoskarkoView Answer on Stackoverflow
Solution 18 - AndroidRico TengView Answer on Stackoverflow
Solution 19 - AndroidSam BainsView Answer on Stackoverflow