このエントリーをはてなブックマークに追加

2010年3月15日月曜日

How to set max length of EditText on source code

[In English]
As you know, we can set max length of EditText on layout xml file,
but in some case I want to set it on source code.

So I looked for setMaxLength method of EditText class,
but this class does not have such kind of method.
Instead of it, it has setFilters method.
The following sample code is how to set max length of EditText.


EditText editText = new EditText(this);
int maxLength = 3;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(FilterArray);




[In Japanese]
皆さんご存知のように、EditTextの最大文字数はレイアウトxmlで指定できます。
ただ、いくつかのケースにおいては、ソースコード上で最大文字数を指定したい場合があります。

そこで、EditTextクラスの"setMaxLength"メソッドを探したのですが、EditTextクラスにはそのようなメソッドはないことが分かりました。
そのようなメソッドの代わりに、setFiltersメソッドを利用して最大文字数を指定するようです。
以下にそのサンプルコードを記載します。


EditText editText = new EditText(this);
int maxLength = 3;
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(maxLength);
editText.setFilters(FilterArray);

0 件のコメント:

コメントを投稿