문제

I have a simple activity with a EditText. I want to save the form data when the user enters a name into the EditText and then hits Enter.

Everything works find except one thing. The keyCode variable is 0 instead of 66 (KeyEvent.KEYCODE_ENTER).

Does anyone have any idéa of what the problem is?

My layout xml:

<EditText
    android:id="@+id/etName"
    style="@style/EditTextFont"
    android:inputType="textPersonName" />

My Activity:

private EditText etName;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.form);

    etName = (EditText) findViewById(R.id.etName);
    etName.setOnEditorActionListener(this);
}

@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
   switch (v.getId()) {
   case R.id.etName:
      // actionId will be EditorInfo.IME_NULL if being called 
      // due to the enter key being pressed.
      if ((event.getAction() == KeyEvent.ACTION_DOWN) && 
            (actionId == EditorInfo.IME_NULL)) {
         save();
         return true;
      }
   }
   return false;
}

Regards, Mattias

도움이 되었습니까?

해결책

From the Android documentation:

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

Called when an action is being performed.

Parameters

v              The view that was clicked.

actionId   Identifier of the action. This will be either the identifier you supplied, or EditorInfo.IME_NULL if being called due to the enter key being pressed.

event       If triggered by an enter key, this is the event; otherwise, this is null.

Returns

Return true if you have consumed the action, else false.

다른 팁

Try with SDK's Enter key instead of using Computer's keyboard key.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top