5

I want to override the back button when the soft keyboard is shown. Basically when the back button is hit, I want the keyboard to dismiss, and I want to append some text onto whatever the user has typed in that edit text field. So basically I need to know when the keyboard is dismissed. After searching around, I realized there is no API for this, and that the only real way to do this would be to make your EditText class.

So I created my own EditText class and extended EditText like this

public class CustomEditText extends EditText
{

    public CustomEditText(Context context)
    {
        super(context);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init();
    }

    private void init()
    {

    }

}

I have also added this method

    @Override
        public boolean dispatchKeyEventPreIme(KeyEvent event)
        {
            if (KeyEvent.KEYCODE_BACK == event.getKeyCode())
            {
                Log.v("", "Back Pressed");

                            //Want to call this method which will append text
                            //init();
            }
            return super.dispatchKeyEventPreIme(event);
        }

Now this method does override the back button, it closes the keyboard, but I dont know how I would pass text into the EditText field. Does anyone know how I would do this?

Also another quick question, does anyone know why this method is called twice? As you can see for the time being, I have added a quick logcat message to test it works, but when I hit the back button, it prints it twice, any reason why it would be doing this?

Any help would be much appreciated!!

AdamM
  • 4,400
  • 5
  • 49
  • 95

2 Answers2

5

This is due to the dispatchKeyEventPreIme being called on both ACTION_DOWN and ACTION_UP.
You will have to process only when KEY down is pressed. So use

if(event.getAction () == KeyEvent.ACTION_DOWN)

Edit: for the first question You could do

setText(getText().toString() + " whatever you want to append"); 

in dispatchKeyEventPreIme

nandeesh
  • 24,740
  • 6
  • 69
  • 79
  • Ah, silly me, should have realized that. But in regards to my other question. Do you know how I would pass text to the EditText field when the keyboard is dismissed? – AdamM Aug 15 '12 at 08:33
4

Why twice? Probably the method is called on press down and up event.

Piotr Ślesarew
  • 2,826
  • 1
  • 17
  • 17