Android custom EditText and back button override

烈酒焚心 提交于 2019-12-10 14:52:56

问题


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


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/11965961/android-custom-edittext-and-back-button-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!