I would like to see the maxLength
of an EditText
at run time to be able to make a text display decision.
Is that possible?
Here is a description of what I wan't to do.
I have a ListView with many rows and each row have an EditText and a TextView.
I've made a subclass of ArrayAdapter to be able to feed the String that I want to place in the EditText of each row.
I have set android:maxLength="12"
in the XML file.
I want to display a number in that EditText field, but if the number I want to display has more than android:maxLength="12"
I want to display an "error message" instead.
And I would prefer not to hard code that 12 in my subclass of ArrayAdapter.
There is probably a simple solution, but I haven't found it yet.
(android first time...)
This should work:
From api 21 you can do it like that:
I hope this helps someone.
Kind of complicated, but I don't know of any other approach. I hope it works (not tested):
extend the edit text and retrieve the value from the attributeset in the constructor.
public class MyEditText extends EditText {
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:
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:where
maxLength
is the Integer you're interested in finding, parsed from the xml attribute (android:maxLength="@integer/max_length"
). ThisInputFilter.LengthFilter
has only one field (private int mMax
) and no accessor method.How It Can Be Done
TextView
and returning anint
.InputFilter
set on theTextView
and find one belonging to theInputFilter.LengthFilter
implementation.This would give you something like this:
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.Only limited parameters have their getters, so I don't think you can read it .
So write length (Say 12) in values folder and use it in xml layout and arrayAdapter . Now its not hard-coded .
1)Create integer.xml in values *
2)In layout
3) in ArrayAdapter :