Overriding Back Button Action in Activity

只愿长相守 提交于 2020-01-06 02:23:08

问题


I have just overide my back button in my code like this

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {

                return true;
            }
            return super.onKeyDown(keyCode, event);
        }

        @Override
        public boolean onKeyUp(int keyCode, KeyEvent event)
          {

                 {
                       startActivity(new  Intent(context, MainDialog.class));
                       finish();

                return true;
            }
            return super.onKeyUp(keyCode, event);
        }

Now I am facing a weird problem, I have a edit text on the current Activity. At the time of editing when I am trying to close the virtual keyboard by pressing the back button . My Application finishes... But I just want to close the keyboard not the Avtivity.. Any suggestion to solve my issue..?

Thanks in advance, Tanmay


I have tried both 

       @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) 
        {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

               startActivity(new  Intent(context, MainDialog.class));
               finish();
               return true;
        }
        return super.onKeyUp(keyCode, event);
    }

and

        @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) 
        {
        if (keyCode == KeyEvent.KEYCODE_BACK ) {

               startActivity(new  Intent(context, MainDialog.class));
               finish();
               return true;
        }
        return super.onKeyUp(keyCode, event);
    }

But no result. Any suggestion!!


回答1:


It seems you missed the if statement that catches the back key code. Try this:

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            startActivity(new  Intent(context, MainDialog.class));
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }



回答2:


One more solution probably, can we do like this...

I have an ImageButton by id buttonBack in xml I am getting hold of that on btnBack and adding an OnClickListener

In public void onClick function I call an intent of the class which is having another layout probably the previous one class...hope this works for all... thanks.

ImageButton btnBack = (ImageButton)this.findViewById(R.id.buttonBack);
    btnBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
        Intent myIntent = new Intent(view.getContext(), Your.class);
                    startActivityForResult(myIntent, 0);

        }
    });


来源:https://stackoverflow.com/questions/4074979/overriding-back-button-action-in-activity

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