其他分享
首页 > 其他分享> > Android入门教程 | EditText 用户输入

Android入门教程 | EditText 用户输入

作者:互联网

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 有:

例:假设有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已有内容的长度范围内。

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零基础入门教程视频参考

标签:mEt1,IME,int,EditText,入门教程,EditorInfo,ACTION,Android,public
来源: https://www.cnblogs.com/andyour/p/15432748.html