レイアウトにハードコーディングしたくないので、のmaxLengthプロパティをプログラムで設定しTextViewたいと思います。にset関連するメソッドが表示されませんmaxLength。
これを達成する方法を誰かが私に案内できますか?
レイアウトにハードコーディングしたくないので、のmaxLengthプロパティをプログラムで設定しTextViewたいと思います。にset関連するメソッドが表示されませんmaxLength。
これを達成する方法を誰かが私に案内できますか?
回答:
そのようなものでなければなりません。しかし、textviewには使用せず、edittextのみを使用します。
TextView tv = new TextView(this);
int maxLength = 10;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
tv.setFilters(fArray);editText.filters = arrayOf(*editText.filters, InputFilter.LengthFilter(10))コトリンで古いフィルターを維持する
                    これを試して
int maxLengthofEditText = 4;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});Kotlinをご利用の方
fun EditText.limitLength(maxLength: Int) {
    filters = arrayOf(InputFilter.LengthFilter(maxLength))
}次に、単純なeditText.limitLength(10)を使用できます
ジョアン・カルロス Kotlinの使用で、言いました:
editText.filters += InputFilter.LengthFilter(10)一部のデバイスの奇妙な動作については、https://stackoverflow.com/a/58372842/2914140も参照してください。
(に追加android:inputType="textNoSuggestions"しますEditText。)
LengthFilter(10))、次に別のフィルターを追加する必要があります(LengthFilter(20))。
                    Kotlinの場合、以前のフィルターをリセットしない場合:
fun TextView.addFilter(filter: InputFilter) {
  filters = if (filters.isNullOrEmpty()) {
    arrayOf(filter)
  } else {
    filters.toMutableList()
      .apply {
        removeAll { it.javaClass == filter.javaClass }
        add(filter)
      }
      .toTypedArray()
  }
}
textView.addFilter(InputFilter.LengthFilter(10))これに簡単な拡張機能を作りました
/**
 * maxLength extension function makes a filter that 
 * will constrain edits not to make the length of the text
 * greater than the specified length.
 * 
 * @param max
 */
fun EditText.maxLength(max: Int){
    this.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(max))
}editText?.maxLength(10)     AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Title");
                    final EditText input = new EditText(this);
                    input.setInputType(InputType.TYPE_CLASS_NUMBER);
//for Limit...                    
input.setFilters(new InputFilter[] {new InputFilter.LengthFilter(3)});
                    builder.setView(input);元の入力フィルターを維持するには、次のようにします。
InputFilter.LengthFilter maxLengthFilter = new InputFilter.LengthFilter(100);
        InputFilter[] origin = contentEt.getFilters();
        InputFilter[] newFilters;
        if (origin != null && origin.length > 0) {
            newFilters = new InputFilter[origin.length + 1];
            System.arraycopy(origin, 0, newFilters, 0, origin.length);
            newFilters[origin.length] = maxLengthFilter;
        } else {
            newFilters = new InputFilter[]{maxLengthFilter};
        }
        contentEt.setFilters(newFilters);