处理在不同设备上的EditText中输入密钥

Sco*_*ott 10 android android-layout android-edittext

现在我正在使用onEditorActionListener处理我的EditText字段中的enter键,并查看IME_NULL的Action ID.它适用于所有用户,除了一个.她有一个Xperia Arc.

TextView.OnEditorActionListener keyListener = new TextView.OnEditorActionListener(){
  public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    if(actionId == EditorInfo.IME_NULL){
      if(((EditText)findViewById(view.getId())) == ((EditText)findViewById(R.id.etUser))){
        ((EditText) findViewById(R.id.etPass)).requestFocus();
      }
      if(((EditText)findViewById(view.getId())) == ((EditText)findViewById(R.id.etPass))){
        logon();
      }
    }
  return true;
  }
};
Run Code Online (Sandbox Code Playgroud)

在了解了这个问题后,我尝试了另一种方法,使用onKeyListener并查找键事件ACTION_DOWN,然后检查键码是否与KEYCODE_ENTER匹配.

EditText etUserName = (EditText) findViewById(R.id.etUser);
etUserName.setOnKeyListener(new OnKeyListener() {
  public boolean onKey(View view, int keyCode, KeyEvent event){
    if (event.getAction() == KeyEvent.ACTION_DOWN){
      switch (keyCode)
      {
        case KeyEvent.KEYCODE_DPAD_CENTER:
        case KeyEvent.KEYCODE_ENTER:
          if(((EditText)findViewById(view.getId())) == ((EditText)findViewById(R.id.etUser))){
            ((EditText) findViewById(R.id.etPass)).requestFocus();
          }
          return true;
        default:
          break;
      }
    }
    return false;
  }
});
Run Code Online (Sandbox Code Playgroud)

也没有骰子.我现在不知所措.有很多应用程序可以正常处理回车键.他们有什么不同的做法?

Sco*_*ott 17

我想出了如何让它发挥作用.

我不得不将android:singleLine ="true"添加到布局XML中的EditText标记中(或者你可以在代码中使用setSingleLine()来设置它).这会强制编辑文本仅使用一行,焦点将转到下一个EditText框.


jsw*_*jsw 7

试试这个解决方案:(我还没有测试过)

将以下属性设置为您的 EditText

android:imeOptions="actionNext"
Run Code Online (Sandbox Code Playgroud)

现在您可以设置以下内容 onEditorAction

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_NEXT) {
        // Program Logic Here
        return true;    
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

对于某些其他功能,您可以将密码设置EditText为:

android:imeOptions="actionDone"
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

TextView.OnEditorActionListener keyListener = new TextView.OnEditorActionListener(){
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_NEXT) {
                ((EditText) findViewById(R.id.etPass)).requestFocus();
            }
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                logon();
            }
            return true;
        }
    };
Run Code Online (Sandbox Code Playgroud)