24

I am trying to have an EditText with the following characteristics when editing with a soft key. I ready the documentation, searched here, play with the parameters but could not find a working configuration.

  1. The EditView view on the screen has height for a few lines (e.g. 3-4).
  2. The content text is a single line (that is, no line breaks).
  3. If the content text is longer than the view's width it should wrap to next line
  4. The Enter key of the soft key shows the Done action label.

I could achieve {1,2,3} and {1,2,4} but not {1,2,3,4}. My rational is that since the content is a single line (no line breaks) the Enter key is not used and thus should be able to be changed to the Done label.

My setup code looks like this

editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
editText.setHorizontallyScrolling(false);
editText.setSingleLine(false);
// This does not work. Soft keyboard has Enter action.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

Is it possible? Any suggestion?

Janusz
  • 187,060
  • 113
  • 301
  • 369
user1076637
  • 768
  • 5
  • 15

2 Answers2

38

This combination (and the specific order of the EditText method calls) should produce the configuration that you want:

  editText.setInputType(
    InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
  editText.setSingleLine(true);
  editText.setLines(4); // desired number of lines
  editText.setHorizontallyScrolling(false);
  editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
Joe
  • 14,039
  • 2
  • 39
  • 49
  • AWESOME! Virtual hug for you :) – Kevin Parker Sep 11 '14 at 05:51
  • 3
    to change height dynamically use setMaxLines instead – user2798694 Dec 17 '15 at 17:04
  • Thx for correct answer, as others told EditText have hidden implicit contracts when setting it's properties so operation order is important. To achieve starting with single line EditText and than autowrap to next line until maxLines are reached just replace: editText.setLines(4) ; with: editText.setMaxLines(maxLines = 5); – xyman Jan 25 '17 at 14:39
  • @Joe Thank you for your answer. Would you please be so nice and expand your answer and explain how on earth did you come up with that combination. Very useful. – f470071 Apr 28 '17 at 07:07
9

Just add

editText.setHorizontallyScrolling(false);
editText.setMaxLines(Integer.MAX_VALUE);

with your edittext instance in your activity programmatically.

It configures the EditText instance so that the user edits a single-line string that is displayed with soft-wrapping on multiple lines with IME options.

Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
  • 2
    Just to be clear, you cannot set these values in your layout XML--they will be ignored. Set them programmatically just like the OP says to. – Evan Aug 31 '17 at 16:00