0

我想要檢測何時按下軟鍵「完成」,以便在此時顯示烤麪包消息。我看到這個帖子提出了同樣的問題here但是,我很困惑如何實施解決方案。Android:按下軟按鍵上的「完成」鍵時檢測

提供的解決方案是:

editText = (EditText) findViewById(R.id.edit_text); 

editText.setOnEditorActionListener(new OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
     if (actionId == EditorInfo.IME_ACTION_DONE) { 
      // toast message 
     } 
     return false; 
    } 
}); 

我的問題是這樣的:

  1. 是EDITTEXT假設onCreate方法下被定義?
  2. 是整個代碼假設是在onCreate方法?

回答

1

總之,是的。除非你只想在某些條件下激活EditText,否則你可以把它放在EditText發揮作用的地方(如點擊事件,可運行或網絡調用之後),它會歸結爲偏好。

1

你可以把你的EditText任何你喜歡的地方。我傾向於將所有東西都分成更小的方法,因爲我認爲它使代碼更易於更改,但幾乎所有東西都放在onCreate方法中是非常普遍的做法,因爲它使代碼更易於在不跳回介於不同的方法之間。

0

editText = (EditText) findViewById(R.id.edit_text);

這必須調用後setContentView

坐落在上編輯文本ImeOption 佈局否則你永遠也趕不上做完這些動作。

public ... extends Activity 
{ 

public void onCreate(Bundle ...) 
{ 
super... 
setContentVIew... 


editText = (EditText) findViewById(R.id.edit_text); 

editText.setOnEditorActionListener(new OnEditorActionListener() { 
    @Override 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
     if (actionId == EditorInfo.IME_ACTION_DONE) { 
      // toast message 
     } 
     return false; 
    } 
}); 

} 
} 

<EditText 
      android:id="@+id/edittext1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:imeOptions="actionDone" 
      > 
0

進口:

import android.view.View.OnKeyListener; 

嘗試用下面的代碼上perticular編輯文本的關鍵時候。

代碼:

ed.setOnKeyListener(new OnKeyListener() { 

@Override 

public boolean onKey(View v, int keyCode, KeyEvent event) { 

      // TODO Auto-generated method stubi 

      Log.d("View", "conLL.getWidth() "+conLL.getWidth()); 

      if (event.getKeyCode()==66 && enteredNumber>0) { 

      Log.d("View", "------------------------ "); 

      } 
      return false; 
     } 
});