AndroidでEditTextに制限をかける方法
本稿ではEditTextに制限をかける方法を解説していきます。
EditTextに文字数制限をかけるには?
EditText内の入力文字数に制限をかけたい場合は、XmlとJavaコード内で行う2つの方法があります。
EditTextにXmlで文字数制限をかける方法
maxLengthプロパティを使用します。
下記コードですとmaxLengthを10としていますので、10文字以下しかEditTextに入力できません。
<EditText
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLength="10" />
EditTextにJavaで文字数制限をかける方法
EditText内の文字数制限を行ったり、文字列を大文字or小文字にするクラスであるInputFilterを使用します。
EditText edit = (EditText)findViewById(R.id.edit);
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(10);
edit.setFilters(filters);
EditTextに入力制限をかけるには?
こちらも文字数制限と同様にXmlとJavaコード内で行う2の方法がありますが、
ここでは割愛してxmlのみを説明します。
EditTextにXmlで入力制限をかける方法
inputTypeプロパティを使用して入力させたい文字種別を指定します。
下記のコードですとinputTypeがnumberになっていますので、数値の入力指定となります。
<EditText
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="10" />
inputTypeで指定できる属性一覧
属性 | 入力種別 |
---|---|
date | 日付 |
datetime | 日時 |
none | 入力できない |
number | 数値 |
numberDecimal | 10進数 |
numberPassword | 数値パスワード |
numberSigned | 符号付番号 |
phone | 電話番号 |
text | テキスト |
textAutoComplete | オートコンプリート対応 |
textAutoCorrect | 自動修正 |
textCapCharacters | 全文字の大文字化 |
textCapSentences | 最初の文字の大文字化 |
textCapWords | 全ての単語の最初の文字の大文字化 |
textEmailAddress | メールアドレス |
textEmailSubject | メールアドレス件名 |
textFilter | データをフィルタリングしているテキスト |
textImeMultiLine | 複数行のテキスト |
textLongMessage | 長いメッセージのテキスト |
textMultiLine | 複数行のテキスト |
textNoSuggestions | IMEの辞書ベースの単語候補を表示しない |
textPassword | パスワードテキスト |
textPersonName | 人名テキスト |
textPhonetic | 音声発音用のテキスト |
textPostalAddress | 郵送先住所テキスト |
textShortMessage | ショートメッセージのテキスト |
textUri | URIとして使用されるテキスト |
textVisiblePassword | 表示パスワード |
textWebEditText | Webフォームのテキスト |
textWebEmailAddress | WebフォームのEメールアドレス |
textWebPassword | Webフォームのパスワード |
time | 時間 |
スポンサーリンク