Monday, April 9, 2012

Handling soft keyboard done button

A common Android task is adding data to an app via an EditText. Some guis will have an add button, but others just use the keyboard done button to commit the new item to a list or database or submit to a server. In the latter case, you need to listen for the clicking of the DONE button on the keyboard. This is easily handled by 1. adding to the edittext xml definition the following line android:imeOptions="actionDone" 2. Attaching a setOnEditorActionListener(new OnEditorActionListener() method to the edittext in the activity The example below shows how to do this. Another option for the Java code is to create a separate OnEditorListener class and use that to process the onDone. The blog article below shows how to do that. I haven't tested the code but eyeballing it looks like it'll work or at least get you merrily along the way. It's a little bit cleaner implementation and allows for code reuse if you're going to have multiple activities with similar processing needs. http://savagelook.com/blog/android/android-quick-tip-edittext-with-done-button-that-closes-the-keyboard#comments
 <EditText  
           android:id="@+id/addTodoListEntryET"  
           android:layout_width="wrap_content"  
           android:layout_height="wrap_content"  
           android:layout_gravity="center_vertical"  
           android:hint="@string/practiceScheduleCustomAddSection"  
           android:singleLine="true"  
           android:imeOptions="actionDone" />  
 mAddTodoListEntryET = (EditText) findViewById(R.id.addTodoListEntryET);  
 mAddTodoListEntryET.setOnEditorActionListener(new OnEditorActionListener()  
 {  
 @Override  
 public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2)  
 {  
       // hide the keyboard  
      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
      imm.hideSoftInputFromWindow(arg0.getWindowToken(), 0);  
      // do your work here  
      String listItem = mAddTodoListEntryET.getText().toString();  
      if (listItem!=null && listItem.length()>1) {  
           if (CustomApplication.DEBUG) Log.d(TAG, "Item added to TodoList"+ listItem);  
           int nextOrder = mItems.size();  
           try {  
           if (nextOrder!=0) {  
                Entry last = mItems.get( nextOrder-1);  
                nextOrder= last.getOrdering();  
           }  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
           Entry guide = new Entry();  
           entry.setTitle(listItem);  
           entry.setOrdering(nextOrder+1);  
           entry.setCompleted(false);  
           mItems.add(guide);  
           handler.sendEmptyMessage(1);  
           // clear the text  
           mAddTodoListEntryET.setText("");  
      }  
       return false;  
   }  
 });