使用android中的edittext处理软键盘中的键事件

时间:2013-07-01 05:49:48

标签: android

我尝试在android中处理事件软键盘但是当我按下回车键时永远不会产生任何我做的事情?请对我的代码进行任何编辑。

public class MainActivity extends Activity implements OnKeyListener  {
    EditText editText1;
    EditText editText2;
public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      editText1 = (EditText)findViewById(R.id.editText1);
      editText1.setOnKeyListener(this);
      editText2 = (EditText) findViewById(R.id.editText2);
      editText2.setOnKeyListener(this);
      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

      imm.showSoftInput(editText1, InputMethodManager.SHOW_IMPLICIT);
    }

     public boolean onKey(View view, int keyCode, KeyEvent event) {
      if (event.getAction() == KeyEvent.KEYCODE_ENTER) 
      {
         editText2.setText("hello");      
      }
      return false; // pass on to other listeners.
     }
    }

1 个答案:

答案 0 :(得分:0)

请尝试使用此代码。 editText2.setOnEditorActionListener(new OnEditorActionListener(){

                public boolean onEditorAction(TextView v, int actionId,
                        KeyEvent event) {

                    if (actionId == EditorInfo.IME_ACTION_DONE) {

     editText2.setText("hello");                    
return true;
                    }
                    return false;
                }
            });