Make the “up” button behave like the “back” button on Android

后端 未结 2 1188
闹比i
闹比i 2020-12-23 20:48

The Android app design I\'m working with calls for the \"Up\" button to behave the same way the \"Back\" button behaves, but I\'m not sure how to make that happen.

I

相关标签:
2条回答
  • 2020-12-23 21:19

    from all three of your activities add the following

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
    
        return(super.onOptionsItemSelected(item));
    }
    

    when you press the up button on your app it will invoke onOptionsItemSelected with the id of android.R.id.home just catch that case and manually call onBackPressed()

    0 讨论(0)
  • 2020-12-23 21:44

    KOTLIN

    For anyone coming here in the age of Kotlin, if you set your toolbar up with the NavController, the "Up" button will behave like the back button.

    toolbar.setupWithNavController(findNavController(R.id.nav_host_fragment),findViewById(R.id.full_drawer_layout))
    
    0 讨论(0)
提交回复
热议问题