Create a multiline EditText programmatically

前端 未结 8 1020
無奈伤痛
無奈伤痛 2021-01-03 21:58

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

EditText txt = new EditText(this);    
lp = new LinearLayout.LayoutParams(LayoutParam         


        
相关标签:
8条回答
  • 2021-01-03 22:32

    This should do it

    txt.setSingleLine(false);
    txt.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
    
    0 讨论(0)
  • 2021-01-03 22:35

    Try this

    txt.setLines(number of lines);
    
    0 讨论(0)
  • 2021-01-03 22:38

    On my phone, changing imeOptions and inputType does nothing; setting movementMethod and/or scrollBarStyle will screw the component so badly so that the user will be unable to select any text; isVerticalScrollBarEnabled and isHorizontalScrollBarEnabled does nothing; the best I could do is to use

    txt.setSingleLine(false);
    

    (txt.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION); seems to be unnecessary) but that won't display any scrollbars in the god-damn EditText. Ultimately I gave up and I'm inflating a layout snippet anytime I need a multi-line EditText. Here's the layout:

    <?xml version="1.0" encoding="utf-8"?>
    <EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:inputType="textMultiLine"
    android:lines="4"
    android:minLines="4"
    android:gravity="top|start"
    android:maxLines="4"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:scrollbars="vertical"
    />
    

    And here's Anko snippet:

    fun ViewManager.multiLineEditText(@StyleRes theme: Int = 0, init: EditText.() -> Unit): EditText = ankoView(
        { ctx -> ctx.layoutInflater.inflate(R.layout.util_multilineedittext, this@multiLineEditText as ViewGroup, false) as EditText }, theme, init)
    

    Development on Android sucks so hard.

    0 讨论(0)
  • 2021-01-03 22:47

    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.

    0 讨论(0)
  • 2021-01-03 22:53

    Include this in your code :

    txt.setLines(maxlines);
    

    maxlines will be the maximum number of lines you want to allow in your EditText.

    0 讨论(0)
  • 2021-01-03 22:54

    You may also use this:

    txt.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    
    0 讨论(0)
提交回复
热议问题