Create a multiline EditText programmatically

2020-03-01 04:02发布

I am trying to create a multiline EditText by code. This is what I use:

EditText txt = new EditText(this);    
lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1.0f);
txt.setLayoutParams(lp);
txt.setSingleLine(false); 
txt.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);

But it is still in one single line.

8条回答
smile是对你的礼貌
2楼-- · 2020-03-01 04:10

Combining all above answers was the correct answer so here it is:

texInput.setSingleLine(false);
texInput.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
texInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
texInput.setLines(5);
texInput.setMaxLines(10);
texInput.setVerticalScrollBarEnabled(true);
texInput.setMovementMethod(ScrollingMovementMethod.getInstance());
texInput.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
查看更多
我想做一个坏孩纸
3楼-- · 2020-03-01 04:12

Try this

txt.setLines(number of lines);
查看更多
别忘想泡老子
4楼-- · 2020-03-01 04:19

You may also use this:

txt.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
查看更多
淡お忘
5楼-- · 2020-03-01 04:20

This should do it

txt.setSingleLine(false);
txt.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
查看更多
Summer. ? 凉城
6楼-- · 2020-03-01 04:27

In addition to the above suggestions - you might want to set the below additional parameters if you are not able to get this working

texInput.setHorizontallyScrolling(false);
texInput.setHorizontalScrollBarEnabled(false);

If you are changing the height of the edittext programmatically then you might want to request a layout too by calling requestLayout().

查看更多
Explosion°爆炸
7楼-- · 2020-03-01 04:31

The combination that finally worked for me was:

answerView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE);
answerView.setSingleLine(false);

At least partially I was using setInputType for configuring several different options so it made more sense than some of the other possibilities.

查看更多
登录 后发表回答