Scheming with the Coco and Android

A dependable way to respond to the <enter-key> in an EditText is with a TextWatcher, a LocalBroadcastManager, and a BroadcastReceiver. I think you need to add the v4 support library to use the LocalBroadcastManager. I use the tutorial at 7.3 “Local broadcast events with LocalBroadcastManager” because of its complete concise code Example. In onTextChanged before is <the index of the end of the change before the change>minus start. When in the TextWatcher the UI thread is busy updating editText’s editable, so we send an Intent to wake up the BroadcastReceiver when the UI thread is done updating editText.

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
in onCreate:
editText.addTextChangedListener(new TextWatcher() {
  public void onTextChanged
  (CharSequence s, int start, int before, int count) {
    //check if exactly one char was added and it was an <enter>
    if (before==0 && count==1 && s.charAt(start)=='\n') {
    Intent intent=new Intent("enter")
    Integer startInteger=new Integer(start);
    intent.putExtra("Start", startInteger.toString()); // Add data
in the BroadcastReceiver's onReceive:
int start=Integer.parseInt(intent.getStringExtra("Start"));
editText.getText().replace(start, start+1,""); //remove the <enter>
//respond to the <enter> here
§634 · April 21, 2013 · Android · · [Print]

Leave a Reply