You can get the Field value using the Reflection API.
Why You Shouldn't Do It
Just about everyone would advocate against it (including me) because:
- It's slow
- It's implementation-dependant
- It's not intended to be accessed (obviously)
As of now, looking at the source code (Android API 19), the implementation depends on an
InputFilter.LengthFilter
which is set in the constructor as:
if (maxlength >= 0) {
setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });
} else {
setFilters(NO_FILTERS);
}
where maxLength
is the Integer you're interested in finding, parsed from the xml attribute (android:maxLength="@integer/max_length"
).
This InputFilter.LengthFilter
has only one field (private int mMax
) and no accessor method.
How It Can Be Done
- Declare a static method in a relevant utility class accepting a
TextView
and returning an int
.
- Iterate over each
InputFilter
set on the TextView
and find one belonging to the InputFilter.LengthFilter
implementation.
- Access, get and return the mMax field's value using Reflection.
This would give you something like this:
import java.lang.reflect.Field;
// [...]
public static int getMaxLengthForTextView(TextView textView)
{
int maxLength = -1;
for (InputFilter filter : textView.getFilters()) {
if (filter instanceof InputFilter.LengthFilter) {
try {
Field maxLengthField = filter.getClass().getDeclaredField("mMax");
maxLengthField.setAccessible(true);
if (maxLengthField.isAccessible()) {
maxLength = maxLengthField.getInt(filter);
}
} catch (IllegalAccessException e) {
Log.w(filter.getClass().getName(), e);
} catch (IllegalArgumentException e) {
Log.w(filter.getClass().getName(), e);
} catch (NoSuchFieldException e) {
Log.w(filter.getClass().getName(), e);
} // if an Exception is thrown, Log it and return -1
}
}
return maxLength;
}
As mentioned earlier, this will break if the implementation that sets the maximum length of the TextView
changes. You will be notified of this change when the method starts throwing. Even then, the method still returns -1, which you should be handling as unlimited length.