To set the max length of the EditText (pick one or the other):
In your XML file (recommended), use the property android:maxLength="150"
Ex:
<EditText
android:id="@+id/yourEditTextId"
...
android:maxLength="150" />
Programmatically (in your onCreate
method), like so:
EditText et = (EditText)findViewById(R.id.yourEditTextId);
et.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(150) // 150 is max length
});
To keep a counter of the length left in the EditText:
Add this listener in your onCreate
method (or anywhere, but it makes sense in onCreate
):
final EditText et = (EditText)findViewById(R.id.yourEditTextId);
et.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
TextView tv = (TextView)findViewById(R.id.yourTextViewId);
tv.setText(String.valueOf(150 - et.length()));
}
@Override
public void onTextChanged(CharSequence s, int st, int b, int c)
{ }
@Override
public void beforeTextChanged(CharSequence s, int st, int c, int a)
{ }
});