EditText with number keypad by default, but allowing alphabetic characters

痞子三分冷 提交于 2019-11-26 05:53:38

问题


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?


回答1:


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.




回答2:


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

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>



回答3:


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)




回答4:


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.




回答5:


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"/>



回答6:


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




回答7:


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.




回答8:


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.




回答9:


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.




回答10:


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">




回答11:


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.




回答12:


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.




回答13:


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;
              }
         }
     }
}  



回答14:


You can try setting---

editText.setRawInputType(Configuration.KEYBOARD_QWERTY);

for more description




回答15:


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" />



回答16:


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.




回答17:


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;
    }
});



回答18:


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);
        }
    }
}



回答19:


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.



来源:https://stackoverflow.com/questions/3544214/edittext-with-number-keypad-by-default-but-allowing-alphabetic-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!