【问题标题】:handling enter key press in editText [duplicate]处理editText中的输入键[重复]
【发布时间】:2017-04-26 13:57:02
【问题描述】:

我试图让用户在编辑文本中输入文本。当用户按回车键时,我想从编辑文本中获取文本并将其添加到我的 ArrayList 中。我在从编辑文本中控制 keyEvent 时遇到问题。

public class MainActivity extends Activity {
ArrayList<String> array_list;
ListAdapter lv;
ListView list;
EditText edittext;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    array_list = new ArrayList<String>();
    edittext = (EditText) findViewById(R.id.textView);
    lv = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array_list);
    list = (ListView) findViewById(R.id.lstView);

    list.setAdapter(lv);
    edittext.requestFocus();

    edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_GO) {
                array_list.add(edittext.getText().toString());
                edittext.setText("");
                edittext.requestFocus();
            }
            return handled;
        }
    });
}
}

所以我需要做的是当用户按下回车键时,它会从字段中获取文本并将其添加到 arrayList。然后它会从文本字段中删除文本并重新获得焦点。

【问题讨论】:

  • 请出示您的代码?很难猜出您的问题。
  • 我见过人们使用 onKeyListeners 和 textWatchers。我只是想知道哪个最容易使用以及如何实现它。
  • 他们实际上做了不同的事情。 OnKeyListener 将听取某些键盘键并采取行动,另一方面,TextWatcher 只接收新文本并且可能不会接收 \n 字符,除非 EditText 设置为多行。无论如何,我相信OnKeyListener 是最好的方法。
  • I am having issues controlling the keyEvent from the edit text. 确实不够具体
  • @njzk2 我添加了代码来展示我所写的内容。

标签: java android android-edittext


【解决方案1】:
editText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    boolean handled = false;
    if (actionId == EditorInfo.IME_ACTION_GO) {
        //Perform your Actions here.

    }
    return handled;
   }
});

在您的 xml 中,您可以执行以下操作:

<EditText
    android:id="@+id/editText2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text|textUri"
    android:imeOptions="actionGo"
    android:imeActionId="666" 
    android:imeActionLabel="Some Label"
    android:maxLines="1"/>

其中的关键是包含android:ime...xml

【讨论】:

  • 我已经在我的代码中实现了这两个,当按下回车按钮时代码没有执行
  • 显然你必须指定android:maxLines="1",否则它只是输入换行命令。也许它与你使用的键盘或其他东西有关,但如果你不需要多行编辑文本我建议你这样使用它。我测试过,它似乎对我有用。我编辑了答案
猜你喜欢
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
  • 2016-03-15
  • 2019-04-29
  • 1970-01-01
  • 2013-04-11
  • 2018-02-13
  • 2015-04-26
相关资源
最近更新 更多