Android EditText 在最大长度时自动聚焦到下一个 EditText

标签 android focus android-edittext

我有一个用户名和密码 XML 段

<EditText 
    android:id="@+id/username"
    android:hint="@string/username_hint"
    android:layout_width="match_parent"
    android:maxLength="9"
    android:nextFocusDown="@+id/pswd"
    android:layout_height="wrap_content">
</EditText>
<EditText 
    android:inputType="textPassword" 
    android:hint="@string/password_hint"
    android:id="@+id/pswd" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content">
</EditText>

我希望当用户名字段到达第9个字符时光标焦点自动跳转到密码字段

我在看 Focus next textview automatically并且正在尝试:

final EditText usr = (EditText) findViewById (R.id.username);
final EditText pswd = (EditText) findViewById (R.id.pswd);
usr.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
        if (s.length() == 9) { 
            pswd.requestFocus(); 
        }
    }
    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start,
    int count, int after) {
    }
});

没有太大的成功。我在处理登录信息的 oncreate 方法中使用了它。如有任何想法或建议,我们将不胜感激。

最佳答案

像这样尝试可能对你有帮助。

/** addTextChangedListener 在第一个用户名框填充到第 9 个字符时有用 * 请求会自动聚焦到下一个框*/

usr.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
         if (count == 9) { 
             pwd.requestFocus(); 
             usr.setTransformationMethod(PasswordTransformationMethod.getInstance());
         }
    }
   @Override
   public void afterTextChanged(Editable arg0) {
   }
   @Override
   public void beforeTextChanged(CharSequence s, int start,
           int count, int after) {
   }
});

关于Android EditText 在最大长度时自动聚焦到下一个 EditText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8318585/

相关文章:

android - 使用 Jetpack Compose for Android 动画形状

c# - 获取焦点窗口名称

android - 为什么我无法获取添加的单选按钮或编辑文本的值?

java - WebView 中视频的全屏按钮不起作用

java - 在 do-while 循环中清除列表

java - 尽管可见,启用为 true,但子 JComponent 不会获得焦点

flutter - 如何抑制 Flutter 中的滚动到 View 行为?

android - android中EditText的多行文本对齐

java - edittext 中的值在获得焦点之前不会显示。安卓

android - 保存包含位图的对象