2012-10-17 168 views
2

有人可以用軟鍵盤幫我輸入密鑰監聽器嗎?Android輸入密鑰監聽器

我需要一個回車鍵監聽器就像一個按鈕,監聽器,將有內部 幾個editext聽衆這樣

enterkey.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View v) { 
     if(editext1.getText().toString().equalsIgnoreCase("test1")) { 
      button3.performClick(); 
     } 
     if(editext1.getText().toString().equalsIgnoreCase("test2")) { 
      button4.performClick(); 
     } 
    } 
); 

我還需要像下面這是正確的?

 if(editext1.getText().toString().equals.null)) { 
      testwrong.setText("Wrong"); 

感謝所有幫助


現在我已經嘗試使用此代碼,但總是收到一個空值時,我打進去嗎? 任何人都可以提出一個解決方案來避免這種情況嗎?

 editext.setOnKeyListener(new View.OnKeyListener() { 
     public boolean onKey(View v, int keyCode, KeyEvent event) { 
      // TODO Auto-generated method stub 
      if (keyCode==KeyEvent.KEYCODE_ENTER) { 
       if("test1".equalsIgnoreCase(anstext.getText().toString())) { 
        but4.performClick(); 
        }} 
       else 
       if("test2".equalsIgnoreCase(editext.getText().toString())) { 
       but5.performClick(); 
       } 

      if("test5".equalsIgnoreCase(editext.getText().toString())) { 
      but6.performClick(); 
      } 

      if("test7".equalsIgnoreCase(editext.getText().toString())) { 
      but7.performClick(); 
      } 
      if (editext.getText().toString() != null){ 
       testwrong.seText("wrong");    } 

     return true; 




     } }); 
+1

請在發佈前格式化你的代碼。 –

+0

問題是什麼? – Blackbelt

回答

7

如果你想趕上用戶按Edittext

yourEditText.setOnKeyListener(new View.OnKeyListener() { 
      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       // TODO Auto-generated method stub 
       if (keyCode==KeyEvent.KEYCODE_ENTER) { //Whenever you got user click enter. Get text in edittext and check it equal test1. If it's true do your code in listenerevent of button3 
        if("test1".equals(edt.getText().toString())) { 
         //paste your code in button3 listener here 
         } 
       } 

} 
    ) 

輸入寄存器onKeyListener這部分是錯誤。

如果(editext1.getText()的toString()equals.null。)){ testwrong.setText( 「錯誤的」);

你應該改變

if (editext1.getText().toString() != null && !editext1.getText().toString().isEmpty()) { 
    // doSomething 
} 
+0

我喜歡這個,但是如果在按下回車鍵的時候如果要在編輯文本框中輸入文本字符串呢? – C0dexe

+0

您想在用戶按下「Enter」鍵時在「EditText」中獲取文本嗎? –

+0

我的意思是,如果編輯文本框中有單詞「test1」,而按下Enter鍵,則執行按鈕單擊按鈕3,謝謝 – C0dexe

16

在你EditText你應該使用imeOptions指定鍵盤動作。

<EditText 
     android:id="@+id/query" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:imeOptions="actionGo" 
     android:inputType="text" /> 

而且在活動的類:

EditText editText = (EditText) findViewById(R.id.query); 
editText.setOnEditorActionListener(new OnEditorActionListener() { 
      public boolean onEditorAction(TextView v, int actionId, 
        KeyEvent event) { 
        if (actionId == EditorInfo.IME_ACTION_GO) { 

         return true; 
        } 
        return false; 
       } 
      });