development

기본적으로 숫자 키패드가있는 EditText,하지만 알파벳 문자 허용

big-blog 2020. 10. 8. 08:15
반응형

기본적으로 숫자 키패드가있는 EditText,하지만 알파벳 문자 허용


나는 EditText 상자가 있고 대부분의 사용자가 숫자를 입력하기 때문에 숫자 키패드로 선택되었을 때 나타나는 기본 키보드를 원합니다 . 그러나 필요한 경우 사용자가 영문자를 입력 할 수 있도록하고 싶습니다. 사용 android:inputType="number"은 입력을 숫자로만 제한합니다. 어떤 옵션이 있습니까?


다음과 같이 xml에서 EditText를 정의하십시오.

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

출력 : android : inputType = "textVisiblePassword"

숫자 행과 나머지 문자.


더 강력한 솔루션을 제안합니다.

사용자에게 입력 유형을 선택할 수있는 기능을 제공합니다.

필요한 수정 사항

- 입력 선택 버튼 표시 / 숨기기 개선

- 입력 유형이 문자 인 경우 제안을 제거 할 수 있습니다.

여기에 이미지 설명 입력

활동은 다음과 같습니다.

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

}

활동의 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>

찾고있는 내용은 다음과 같습니다.

다음 EditText과 같이 xml에서 정의하십시오 .

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

</EditText>

그리고 다음을 호출하십시오 onCreate().

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

EditText지금 을 클릭 할 때마다 숫자와 문자를 입력 할 수 있습니다 ! (숫자 키보드가 먼저 표시됨)


안타깝게도 이는 EditText에 대해 하나의 inputType 만 설정할 수 있기 때문에 불가능합니다. 다음은 버튼에 알파벳 문자 만 표시합니다.

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

그러나 제가 제안 할 수있는 것은 입력 유형을 숫자로 설정하고 숫자 패드에 가까운 양식에 작은 switchKeyboard 버튼을 추가하는 것입니다. 그리고 onClick 설정

editText1.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

사용자가 알파벳 문자로도 전환 할 수 있습니다.


기본적으로 EditText inputtype은 EditText 에서 입력 유형설정하는 데 사용됩니다 .

가능한 값은 다음 android:inputtype과 같습니다.

  • 본문
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • 번호
  • numberSigned
  • numberDecimal
  • 전화
  • 날짜 시간
  • 데이트
  • 시각

그런 다음 예와 같이 모든 값을 사용할 수 있습니다.

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

Asus 태블릿에는 이러한 기능이 있으며 기본 키보드를 사용자 정의했습니다. 그리고 키보드에는 숫자와 알파벳 만 포함되어 있습니다. 귀하의 요구 사항 솔루션은 기본 키보드를 사용자 정의하는 것입니다.


Paresh Mayani 답변을 따를 수 있습니다.

그리고 조언 android:inputType="textPhonetic"에서 사용자 선택에 따라 inputType 텍스트 및 숫자에 사용할 수 있습니다 .

내 요점을 알기를 바랍니다.


활동의 OnCreate에서 다음을 수행하십시오.

    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) {

        }
    });

이 경우 is를 입력하면 numberandroid에 숫자 키보드가 표시되지만 원하는대로 입력 할 수 있습니다. 또한 원하는대로 다른 메서드를 재정의 할 수 있습니다.


내가 그것을 달성 한 방법은 다음과 같습니다 ...

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

숫자로 지정된 문자 만 허용됩니다.

표시된 키보드는 일반 키보드가 아니라 다이얼러의 키보드입니다. 저에게는 XML 내에서 전적으로 필요한 것을 달성했습니다.


이 경우 inputType 필터를 사용하지 말고 EditText 속성에 아래 줄을 추가하십시오.

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "

이제 이러한 문자 만 EditText에 입력 할 수 있습니다. 편집 텍스트의 전체 코드는 다음과 같습니다.

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


다음과 같은 토글 버튼이있는 것은 어떨까요?

  • 숫자 값만 허용하도록 입력 유형을 설정합니다.
  • QWERTY 키보드를 사용할 수 있도록 입력 유형을 설정합니다.
  • 또는 다른 입력 유형 설정 (필요한 경우)

이렇게하면 숫자 키패드를 기본값으로 설정 한 다음 사용자가 버튼을 눌러 변경할 수 있습니다.


현재 기본 Android 입력 유형이 다양한 휴대 전화에서 제공되므로 이는 불가능합니다 .

답변에 일반적으로 포함되는 원시 입력 유형을 설정하는 일반적인 방법과 같이 일부 키보드에서는 작동하지만 다른 키보드에서는 작동하지 않는 가능한 해킹 이 많이 있습니다.

  • editText.setRawInputType(InputType.TYPE_CLASS_NUMBER)

내가 찾을 수있는 가장 좋은 조언은 textPostalAddressXML에서 입력 유형 을 사용하는 것입니다 .

  • 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.


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

You can try setting---

editText.setRawInputType(Configuration.KEYBOARD_QWERTY);

for more description


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

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.


Saurav가 말했듯이, 가장 좋은 방법은 간단한 리스너로 QWERTY 키보드와 숫자 키보 라드 사이를 변경하는 것입니다.

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

나는 모든 방법을 시도하지만 완벽하지는 않습니다. 그래서 다른 생각이 있습니다. 모든 키보드에 완벽하게 작동합니다.

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

EditText의 xml 레이아웃에서 다음 매개 변수를 추가하십시오.

android:inputType="number|text"

이렇게하면 사용자가 텍스트와 숫자를 모두 입력 할 수 있으며 활동이나 조각에 코드를 포함하지 않고 xml에 논리를 포함 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/3544214/edittext-with-number-keypad-by-default-but-allowing-alphabetic-characters

반응형