Android 中的 EditText

来源:互联网 发布:matlab怎么算矩阵 编辑:程序博客网 时间:2024/06/09 21:37

在 Android 中,EditText 作为输入的 UI 视图,是一个比较经常被使用到的控件了。如果仅仅是简单的使用的话,这个视图是比较简单的。不过如果涉及到焦点,就有点麻烦了。正好最近在做的东西和这个有关,分享一下经验。

切换焦点

当我们要在 EditText 输入信息时,要注意的是当前的 EditText 需要有焦点并且是唯一的焦点。网上很多的资料都指出如何获取焦点:

View.requestFocus();

这自然没有错,但是如果目前屏幕上有其它的 EditText 有焦点,那么你输入的时候,其实是输入在其它的 EditText 上的。所以如果目前屏幕上有其它的 EditText 拥有焦点,应该这样处理:

View.clearFocus();View.requestFocus();

否则的话,你会发现光标在目标 EditText 上闪着,可是输入的内容都跑到其它 EditText 上了。甚至是两个 EditText 都出现了光标。
这个方法适用于用户直接在 EditText 上切换的时候。可以配合setOnFocusChangeListener()一起使用。
比如如下:

// OnFocusChange 中的 b 为焦点的状态,如果目前视图拥有焦点则为真,否则为否。// 在 passwordText 获取焦点的时候要判断 usernameText 是否符合规则,不符合则重新输入。passwordText.setOnFocusChangeListener(new View.OnFocusChangeListener() {    @Override    public void onFocusChange(View view, boolean b) {        if (usernameText.getText().toString().length() <= 6 && b) {            passwordText.clearFocus();            usernameText.setText("");            usernameText.requestFocus();        }    }});

通过键盘事件来控制

除了让用户自己来选择以外,还有一种更加友好的互动方式,就是在软键盘上显示相应的提示。可以参考这篇文章。
这样,我们可以通过监听OnEditorActionListener来处理跳转。OnEditorActionListener需要实现onEditorAction方法,而该方法返回一个布尔值。该值如果为真,则焦点保持不变,而如果为否,则切换焦点。所以我们可以这样来实现:

private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {    @Override    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {        if (i == EditorInfo.IME_ACTION_NEXT) {            if (usernameText.getText().toString().length() <= 6) {                // 帐号不满足要求                usernameText.setText("");                return true;            } else {                return false;            }        } else if (i == EditorInfo.IME_ACTION_DONE) {            // 如果输入完成            doSometing();        }        return false;    }};

而为了让其能够起作用,相应的控件应该添加OnEditorActionListener监听。

usernameText.setOnEditorActionListener(mOnEditorActionListener);passwordText.setOnEditorActionListener(mOnEditorActionListener);

最后,为了让软键盘能够提示相应的信息 ,XML 应该添加imeOptions属性,并且只有设置了singleLine属性为真才能起作用。

<EditText    android:id="@+id/usernameText"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:singleLine="true"    android:imeOptions="actionNext"/><EditText    android:id="@+id/passwordText"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:singleLine="true"    android:imeOptions="actionDone"/>

这样,就可以达到相同的效果了。

Thanks For Visit

David Lin

0 0