How to programmatically set maxLength in Android TextView?

老子叫甜甜 提交于 2019-11-26 12:35:57

问题


I would like to programmatically set maxLength property of TextView as I don\'t want to hard code it in the layout. I can\'t see any set method related to maxLength.

Can anyone guide me how to achieve this?


回答1:


Should be something like that. but never used it for textview, only edittext :

TextView tv = new TextView(this);
int maxLength = 10;
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
tv.setFilters(fArray);



回答2:


Try this

int maxLengthofEditText = 4;    
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});



回答3:


Easy way limit edit text character :

EditText ed=(EditText)findViewById(R.id.edittxt);
ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});



回答4:


For those of you using Kotlin

fun EditText.limitLength(maxLength: Int) {
    filters = arrayOf(InputFilter.LengthFilter(maxLength))
}

Then you can just use a simple editText.limitLength(10)




回答5:


For Kotlin and without resetting previous filters:

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



回答6:


As João Carlos said, in Kotlin use:

editText.filters += InputFilter.LengthFilter(10)

You can also see https://stackoverflow.com/a/58372842/2914140 for ZTE Blade A520 strange behaviour.




回答7:


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



回答8:


best solution i found

textView.setText(text.substring(0,10));


来源:https://stackoverflow.com/questions/2461824/how-to-programmatically-set-maxlength-in-android-textview

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