EditText 监听回车

应用EditText时,有时候咱们会须要监听输出的回车,以做出一些操作。 或者须要把回车变成“搜寻”,“发送”或“实现”等等。

EditText 为咱们提供了一个属性 imeOptions 用来替换软键盘中 enter 键的外观,如actionGo 会使外观变成“返回”。 须要同时设置 android:inputType="text"

<EditText    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:imeOptions="actionGo"    android:inputType="text" />

罕用的几个属性以及替换的文本外观:

属性阐明对应动态变量
actionUnspecified未指定EditorInfo.IME_ACTION_UNSPECIFIED
actionNone动作EditorInfo.IME_ACTION_NONE
actionGo去往EditorInfo.IME_ACTION_GO
actionSearch搜寻EditorInfo.IME_ACTION_SEARCH
actionSend发送EditorInfo.IME_ACTION_SEND
actionNext下一项EditorInfo.IME_ACTION_NEXT
actionDone实现EditorInfo.IME_ACTION_DONE

设置的办法能够在布局文件中设置 android:imeOptions="actionNext" 或者在代码中 mUserEdit.setImeOptions(EditorInfo.IME_ACTION_NEXT);

接下来设置回车按键的监听事件 setOnEditorActionListener

et1.setOnEditorActionListener(mOnEditorActionListener);    // ......    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {        @Override        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {            Log.d(TAG, "actionId: " + actionId);            Log.d(TAG, "event:    " + event);            return false;        }    };

如果 onEditorAction 返回 true,示意生产调这个事件。

下面的 actionId 对应的是 android.view.inputmethod.EditorInfo 中的常量。

public static final int IME_ACTION_UNSPECIFIED = 0x00000000;public static final int IME_ACTION_NONE = 0x00000001;public static final int IME_ACTION_GO = 0x00000002;public static final int IME_ACTION_SEARCH = 0x00000003;public static final int IME_ACTION_SEND = 0x00000004;public static final int IME_ACTION_NEXT = 0x00000005;public static final int IME_ACTION_DONE = 0x00000006;public static final int IME_ACTION_PREVIOUS = 0x00000007;

EditText 光标挪动与抉择

次要介绍 setSelection 办法。

setSelection 有:

  • setSelection(int start, int stop) 抉择范畴
  • setSelection(int index) 把光标挪动到指定地位

例:假如有EditText,变量名为mEt1

  • 把光标挪动到最前

    mEt1.setSelection(0);
  • 把光标挪动到最初

    mEt1.setSelection(mEt1.getText().length());
  • 光标右移一位

    mEt1.setSelection(mEt1.getSelectionEnd() + 1);
  • 光标左移一位

    mEt1.setSelection(mEt1.getSelectionEnd() - 1);

    要留神的是,如果传入的index超出了text的范畴,会报 java.lang.IndexOutOfBoundsException
    因而在理论工程中,须要判断传入的地位是否在EditText已有内容的长度范畴内。

  • 全选以后输出的text

    mEt1.setSelection(0, mEt1.getText().length());

监听输出内容

代码中动静限度输出长度
应用TextWatcher

mQueryEt.addTextChangedListener(new TextWatcher() {    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {    }    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {    }    @Override    public void afterTextChanged(Editable s) {        // 如果EditText中的数据不为空,且长度大于指定的最大长度        if (!TextUtils.isEmpty(s) && s.length() > 15) {            // 删除指定长度之后的数据            s.delete(15, s.length() - 1);        }    }});

Android零根底入门教程视频参考