Override back button to act like home button

后端 未结 10 606
小鲜肉
小鲜肉 2020-11-22 08:38

On pressing the back button, I\'d like my application to go into the stopped state, rather than the destroyed state.

In the Android docs it states:

10条回答
  •  囚心锁ツ
    2020-11-22 09:05

    if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

    @Override
    public void onBackPressed() {
    // check if page 2 is open
        RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
        if(page2layout.getVisibility() == View.VISIBLE){
            togglePageLayout(); // my method to toggle the views
            return;
        }else{
            super.onBackPressed(); // allows standard use of backbutton for page 1
        }
    
    }
    

    hope it helps someone, cheers

提交回复
热议问题