Hit the back button but not kill the activity and let it be in Back Stack (Android)

前端 未结 2 1476
难免孤独
难免孤独 2021-01-25 03:48

I have 3 activities A, B and C.

I inflate activity B dynamically on a button click and the user can add as many views as he likes.

The operation is like this:

相关标签:
2条回答
  • 2021-01-25 04:34
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    
            switch(keyCode)
            {
            case KeyEvent.KEYCODE_BACK:
                //bring back the previous activity do your logic here           
                return false;
            }
        return super.onKeyDown(keyCode, event);
    }
    

    You could use this, return false when activity should not be closed. use FLAG_ACTIVITY_REORDER_TO_FRONT to launch the previous activity

    0 讨论(0)
  • 2021-01-25 04:48

    Yes,I agree with Nandeesh.

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
                switch(keyCode)
                {
                case KeyEvent.KEYCODE_BACK:
                    //bring back the previous activity do your logic here           
                    return false; //means you don't want to remove the activity from stack 
                }
            return super.onKeyDown(keyCode, event);  // means u want to remove the last activity from Activity stack.
        }
    
        so question  is that how u can go to other activity without remove it from stack, 
        you can use  :
                    Intent myIntent = new Intent(CurrentClass.this, JumptoActivity.class);
                     startActivity(myIntent);*
    
    example: at the switch case u can use this
    
    if(KeyEvent.KEYCODE_BACK)
    {
                    Intent myIntent = new Intent(CurrentClass.this, NextActivity.class);
                     startActivity(myIntent);
                    return false;
    }
    else
        return true;       //if you not write this then your  menu and other think will be affected.
    

    Thank you I think this little bit information will be helpful for u.

    0 讨论(0)
提交回复
热议问题