1

I want to limit the char per line to 15 chars. After every 15 chars I should include/add a "enter" key pressed ("\n") to the line so that the user can write without stopping. Any suggestion?

This is my EditText xml

<EditText
        android:id="@+id/ET"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:maxLength="20"
        android:inputType="textMultiLine"
        android:visibility="gone" />

This is my ET TextChangedListener

ET.addTextChangedListener(new TextWatcher(){
        @Override
        public void afterTextChanged(Editable s) {}
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {}
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (count % 20 == 0)
            {
                ((Editable) s).append("\n");
                ET.setSelection(ET.getText().length());
            }

        }
    });
Rotary Heart
  • 1,899
  • 3
  • 29
  • 44
  • Why dont you write this programmatically? When it reaches 15 chars then change line – lantonis Jan 20 '14 at 15:32
  • @lantonis because it doesn't change. It includes the "\n", but even when trying to move the cursor to the end it stays at the end of that line – Rotary Heart Jan 20 '14 at 15:35
  • possible duplicate of http://stackoverflow.com/questions/10933412/how-to-set-maximum-characters-per-line-for-text-view-in-android – Daniel Bo Jan 20 '14 at 15:38

2 Answers2

0

You need a custom Text Watcher here, please take help from the following template:

private class CustomTextWatcher implements TextWatcher {
private EditText recieved_et;

public CustomTextWatcher(EditText e) {
    recieved_et = e;
}

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

public void onTextChanged(CharSequence s, int start, int before,
        int count) 
{
    if (count % 20 == 0)
    {
        ((Editable) s).append("\n");
        recieved_et.setText(s.toString());
    }
}   

public void afterTextChanged(Editable s) {
       //Your Implementation
    }
}

Here is how you set this to your Edit Text :

ET.addTextChangedListener(new CustomTextWatcher(ET));
I hope this helps.

Salman Khakwani
  • 6,684
  • 7
  • 33
  • 58
0

You have to add TextWatcher to the EditText programatically.

In the onTextChanged() function you can get the text and if the last line is 20 chars long, use s.append("\n"); function.

You also need to implement the delete functionality I think. If the user deletes a "\n" char you also need to delete the previous one.

You also need to be careful about that function because it can easily stuck in an infinite loop.

tasomaniac
  • 10,234
  • 6
  • 52
  • 84