2

I have an EditText to give user comments.Now I want to input limit will be 500 words. That means user can write comments maximum 500 words. How can i implement this? Please help me.

Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
Helal Khan
  • 867
  • 3
  • 10
  • 25

2 Answers2

9

You could use a TextWatcher to watch the text and not allow it to go beyond 500 words.

Implement your TextWatcher:

final int MAX_WORDS = 500;
final EditText editBox = (EditText) findViewById(<your EditText field>);
editBox.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        // Nothing
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Nothing
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String[] words = s.toString().split(" "); // Get all words
        if (words.length > MAX_WORDS) {
            // Trim words to length MAX_WORDS
            // Join words into a String
            editBox.setText(wordString);
        }
    }
});

Note: You may want to use something from this thread to join the String[] into wordString.

However, this is not the most efficient method in the world, to be frankly honest. In fact, creating an array of the entire String on each key entry may be very taxing, particularly on older devices.

What I would personally recommend is that you allow the user to type whatever they want, then verify it for word count when they hit submit. If it's <=500 words, allow it, otherwise deny it, and give them some kind of message (a Toast?) that tells them.

Lastly, verifying by word count is very iffy. Remember that there are things like &nbsp; (character 160) that can be used as spaces but would not be picked up by this. You are far better to pick a set character limit and restrict the field using the maxLength answers already provided.

Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141
-1

I've tried writing this in XML file but it does not works:

This one works for sure and is actually a better solution to problem and you can also use it for custom validation rules:

InputFilter maxChars = new InputFilter.LengthFilter(500); // 500 Characters editText.setFilters(new InputFilter[] { maxChars });

Saurabh Agrawal
  • 1,355
  • 3
  • 17
  • 33