Android 带有完成操作按钮的多行 EditText

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2986387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:11:15  来源:igfitidea点击:

Multi-line EditText with Done action button

android

提问by kefs

Is it possible to have an EditTextwidget with android:inputType="textMultiLine"set, and android:imeOptions="actionDone"at the same time?

是否可以EditText同时android:inputType="textMultiLine"设置一个小部件android:imeOptions="actionDone"

I'd like a multi-line edit box, with the action button on the keyboard to be Done, not Enter (Carriage Return), but it doesn't seem to be working..

我想要一个多行编辑框,键盘上的操作按钮是完成,而不是 Enter(回车),但它似乎不起作用..

Thanks in advance

提前致谢

回答by alexbtr

Use

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT);

and in XML:

并在 XML 中:

android:inputType="textMultiLine"

回答by HYS

From the android documentation: '"textMultiLine" Normal text keyboard that allow users to input long strings of text that include line breaks (carriage returns).' Therefore the textMultiLine attribute is not appropriate if you want to have the 'Done' button in the keyboard.

来自 android 文档:' “textMultiLine”普通文本键盘,允许用户输入包含换行符(回车)的长文本字符串。' 因此,如果您想在键盘上使用“完成”按钮,则 textMultiLine 属性是不合适的。

A simple way to get a multi-line (in this case 3 lines) input field with the done button is to use EditText with

使用完成按钮获取多行(在本例中为 3 行)输入字段的一种简单方法是将 EditText 与

android:lines="3" 
android:scrollHorizontally="false" 

However, for some reason this only works for me if I do these settings in the code instead of the layout file (in onCreate) by

但是,出于某种原因,如果我在代码中而不是布局文件(在 onCreate 中)中执行这些设置,则这只对我有用

TextView tv = (TextView)findViewById(R.id.editText);
if (tv != null) {
    tv.setHorizontallyScrolling(false);
    tv.setLines(3);
}

I hope this helps someone, as it took quite a while to figure out. If you find a way to make it work from the manifest, please let us know.

我希望这对某人有所帮助,因为花了很长时间才弄明白。如果您从清单中找到了使其工作的方法,请告诉我们。

回答by Anees U

Working Example! Create the below custom EditText class that supports this feature and use the class in the xml file. Working code:

工作示例!创建以下支持此功能的自定义 EditText 类并在 xml 文件中使用该类。工作代码:

package com.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;

public class ActionEditText extends EditText
{
   public ActionEditText(Context context)
   {
       super(context);
   }

   public ActionEditText(Context context, AttributeSet attrs)
   {
       super(context, attrs);
   }

   public ActionEditText(Context context, AttributeSet attrs, int defStyle)
   {
       super(context, attrs, defStyle);
   }

   @Override
   public InputConnection onCreateInputConnection(EditorInfo outAttrs)
   {
       InputConnection conn = super.onCreateInputConnection(outAttrs);
       outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
       return conn;
   }
}

<com.example.ActionEditText
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:imeOptions="actionDone"
       android:inputType="textAutoCorrect|textCapSentences|textMultiLine" />

回答by Lukap

I think this is the way to do you thing. Having android:inputType="textMultiLine", android:imeOptions="actionDone"makes enter key functionality ambiguous. Just keep in mind that you can use android:lines="10"and maybe remove android:inputType="textMultiLine", but depends what you want to achieve sometimes you just need the android:inputType="textMultiLine"and there is no replacement for it.

我认为这是做你的事情的方式。具有android:inputType="textMultiLine"android:imeOptions="actionDone"使输入键功能模棱两可。请记住,您可以使用android:lines="10",也许可以删除android:inputType="textMultiLine",但取决于您想要实现的目标,有时您只需要android:inputType="textMultiLine"并且没有替代品。

EditText ed=new EditText(this);
ed.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_ENTER){
                //do your stuff here
            }
            return false;
        }
});

回答by Ollie C

To do this in Kotlin (and also optionally apply other configurations like textCapSentencesyou can use this extension function:

要在 Kotlin 中执行此操作(并且还可以选择应用其他配置,例如textCapSentences您可以使用此扩展功能:

// To use this, do NOT set inputType on the EditText in the layout
fun EditText.setMultiLineCapSentencesAndDoneAction() {
    imeOptions = EditorInfo.IME_ACTION_DONE
    setRawInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_MULTI_LINE)
}

Usage:

用法:

myEditText.setMultiLineCapSentencesAndDoneAction()

回答by yonez

This seems to work for me perfectly

这似乎对我很有效

int lineNum = 2;
mEditText.setHorizontallyScrolling(false);
mEditText.setLines(3);

回答by Jean Gon?alves

A simple way to work around this situation:

解决这种情况的简单方法:

  • keep this attributes on the EditText:

    android:inputType="textMultiLine" 
    android:scrollHorizontally="false"
    
  • then add this code to only hide the keyboard when ENTER is pressed:

    editText.setOnEditorActionListener(new OnEditorActionListener() 
    {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) 
        {
            editText.setSelection(0);
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);      
            return true;
         } 
         else 
         {
            return false;
         }
         }
    });
    
  • 将此属性保留在 EditText 上:

    android:inputType="textMultiLine" 
    android:scrollHorizontally="false"
    
  • 然后添加此代码以仅在按下 ENTER 时隐藏键盘:

    editText.setOnEditorActionListener(new OnEditorActionListener() 
    {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) 
        {
            editText.setSelection(0);
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);      
            return true;
         } 
         else 
         {
            return false;
         }
         }
    });
    

回答by Gibolt

Reuseable Kotlin Solution

可重复使用的 Kotlin 解决方案

Setting these values in codewas the only thing that worked for me

在代码中设置这些值是唯一对我有用的东西

edittext.inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
edittext.setHorizontallyScrolling(false)
edittext.maxLines = Integer.MAX_VALUE // Or your preferred fixed value

I require this frequently, so made this to keep the code clean:

我经常需要这个,所以这样做是为了保持代码干净:

fun EditText.multilineIme(action: Int) {
    imeOptions = action
    inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE
    setHorizontallyScrolling(false)
    maxLines = Integer.MAX_VALUE
}

// Then just call
edittext.multilineIme(EditorInfo.IME_ACTION_DONE)

If you want to be add an optional custom action on 'Done', try this:

如果您想在“完成”上添加可选的自定义操作,请尝试以下操作:

fun EditText.multilineDone(callback: (() -> Unit)? = null) {
    val action = EditorInfo.IME_ACTION_DONE
    multilineIme(action)
    setOnEditorActionListener { _, actionId, _ ->
            if (action == actionId) {
                callback?.invoke()
                true
            }
            false
        }
    }
}

// Then you can call
edittext.multilineDone { closeKeyboard() }

// or just
edittext.multilineDone()

Need to easily control the keyboard in callback? Read this post

需要在回调中轻松控制键盘?阅读这篇文章

Then add hideKeyboard()call in EditText.multilineDone

然后添加hideKeyboard()调用EditText.multilineDone

回答by Martin Stone

Short answer: No, I believe it's not possible prior to API level 11 (3.0).

简短回答:不,我相信在 API 级别 11 (3.0) 之前是不可能的。

The same issue cropped up here (discussed in the comments to the accepted answer):

同样的问题在这里出现(在对已接受答案的评论中进行了讨论):

Android Soft keyboard action button

Android 软键盘操作按钮

From the final comment:

从最后的评论:

Looking at a few apps on my phone, it seems common to have the multiline box last, with a visible "Done" or "Send" button below it (e.g. Email app).

查看我手机上的一些应用程序,最后显示多行框似乎很常见,其下方有一个可见的“完成”或“发送”按钮(例如电子邮件应用程序)。

回答by twall

If it is not about the look of the on-screen keyboard, you could simply put a input listener on the keyboard and fire the "done"-status if the user inputs a newline.

如果不是关于屏幕键盘的外观,您可以简单地在键盘上放置一个输入侦听器,并在用户输入换行符时触发“完成”状态。