我想以编程方式设置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);
尝试这个
int maxLengthofEditText = 4;
editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLengthofEditText)});
简单的方法限制编辑文本字符:
EditText ed=(EditText)findViewById(R.id.edittxt);
ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
对于那些使用 Kotlin 的人
fun EditText.limitLength(maxLength: Int) {
filters = arrayOf(InputFilter.LengthFilter(maxLength))
}
然后你可以使用一个简单的 editText.limitLength(10)
正如João Carlos所说,在 Kotlin 中使用:
editText.filters += InputFilter.LengthFilter(10)
有关某些设备的奇怪行为,另请参阅https://stackoverflow.com/a/58372842/2914140 。
(添加android:inputType="textNoSuggestions"
到您的EditText
.)
对于 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)
我的 SWIFT 5 解决方案
editText.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(123))
要保留原始输入过滤器,您可以这样做:
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);
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);
我找到的最佳解决方案
textView.setText(text.substring(0,10));