Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Limit The Number of Characters Entered in an Alert Dialog EditText

I know how to limit the size through XML (android:maxLength), but I am dynamically creating an alert dialog in code. Is there something similar I can use? (Prefer to have API 10 compatible solution as well)

I am using the alert dialog to prompt the user for a text value to be shown graphically later.

public void onClickPosition(View v) {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle(R.string.title_Position);
    alert.setMessage(R.string.message_Position);

    final EditText input = new EditText(this);
    input.setText(_currentClass.getPosition());
    alert.setView(input);

    alert.setPositiveButton(R.string.option_Okay, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        _currentClass.setPosition(input.getText().toString());
        TextView textView = (TextView)findViewById(R.id.textPosition);
        textView.setText(_currentClass.getPosition());
      }
    });
like image 306
RiddlerDev Avatar asked Mar 23 '13 23:03

RiddlerDev


2 Answers

You can set the maxLength equivalent in code by means of an InputFilter. Suppose you'd want the EditText to accept a maximum of 20 characters:

input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });

Since setFilters() accepts an array of filters, you can add more than one. Also, for example, if you'd needed more control over what type of characters should be allowed, you could implement your own filter and pass it in with the array.

like image 58
MH. Avatar answered Nov 02 '22 22:11

MH.


try something like this:

InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(MAX_LENGTH);
input.setFilters(FilterArray);
like image 29
ElefantPhace Avatar answered Nov 03 '22 00:11

ElefantPhace