Android - Back button in the title bar

前端 未结 26 2354
南方客
南方客 2020-12-04 07:02

In many apps (Calendar, Drive, Play Store) when you tap a button and enter a new activity, the icon in the title bar turns into a back button, but for the app I am making, i

26条回答
  •  一向
    一向 (楼主)
    2020-12-04 07:27

    1.- Add the activity to AndroidManifest.xml and make sure to provide the meta-data:

    
        
        
    
    

    2.- Add the following code to the onCreate method of the activity:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        getActionBar().setDisplayHomeAsUpEnabled(true);
    } 
    

    3.- Override the onOptionsItemSelected and use NavUtils.navigateUpFromSameTask() static method to navigate throw the stack.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    However, using navigateUpFromSameTask() is suitable only when your app is the owner of the current task (that is, the user began this task from your app). If that's not true and your activity was started in a task that belongs to a different app, then navigating Up should create a new task that belongs to your app, which requires that you create a new back stack.

提交回复
热议问题