我有一个用户名和密码 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/