Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom EditText and back button override

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!!

like image 554
AdamM Avatar asked Aug 15 '12 08:08

AdamM


1 Answers

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

like image 77
nandeesh Avatar answered Sep 27 '22 18:09

nandeesh