【问题标题】:How to Handle Enter Key Using TextWatcher on Android如何在 Android 上使用 TextWatcher 处理 Enter 键
【发布时间】:2012-10-04 14:07:20
【问题描述】:

我正在使用 Android。以前我使用onKeyListener 来处理对关键事件的特定操作。

但是,这种方式似乎不能解决我的问题,因为一旦我为我的EditText 实现了那个监听器,几乎所有的键都会被禁用。在阅读了 SO 中的一些主题后,我知道我应该改用 TextWatcher,但我仍然想知道如何处理内部的 ENTER 键事件,因为提供的参数只有 CharSequence、Editable 等。我没有找不到任何keyCode 参数。

【问题讨论】:

  • However, this way seems not to solve my problem since almost all key would get disable once i have implemented that listener to my EditText...seams 比如你的代码不正确。它应该工作。使用text watcher 你不能得到Enter event
  • 为什么我的问题被否决了?

标签: android android-edittext keylistener textwatcher


【解决方案1】:

我认为这是更好的解决方案,因为您可以在 EditText 字段的任何位置按“Enter”,而不仅仅是在行尾。

    edittext.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int st, int ct,
                                      int af) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() < 1 || start >= s.length() || start < 0)
                return;

            // If it was Enter
            if (s.subSequence(start, start + 1).toString().equalsIgnoreCase("\n")) {

                // Change text to show without '\n'
                String s_text = start > 0 ? s.subSequence(0, start).toString() : "";
                s_text += start < s.length() ? s.subSequence(start + 1, s.length()).toString() : "";
                edittext.setText(s_text);

                // Move cursor to the end of the line
                edittext.setSelection(s_text.length());
            }
        }
    });

【讨论】:

【解决方案2】:

试试这个

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if (s.length()>0 && s.subSequence(s.length()-1, s.length()).toString().equalsIgnoreCase("\n")) {
        //enter pressed
    }
}

【讨论】:

  • @user2348959 该方法不适合此目的。如果你用退格向上移动一行,这也会被调用。
  • @user2348959 如果新行出现在字符串的末尾,它可以工作。但它不起作用 新行出现在字符串之间
【解决方案3】:

试试这个

protected View.OnKeyListener onEnter = new View.OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
            //here do what you want
        }
        return false; // very important
    }
};

【讨论】:

  • 根据文档:将硬件密钥分派到视图时调用。
  • 正如 Divers 所说,KeyListener 实际上会监听硬件按键(音量、家庭等)。
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 2020-09-30
相关资源
最近更新 更多