Android - Back button in the title bar

前端 未结 26 2426
南方客
南方客 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:30

    I needed to mix some answers to get the right answer for me because my app has 3 activities that can go and back at any time. Activity1 > Activity2 > Activity3. When I was doing something on my activity3, the back button was backing correctly to Activity2. However, from the Activity2, using finish(), it was backing to Activity3 and not Activity1. And I'm extending AppCompatActivity. So, my solution was:

    public class Activity2 extends AppCompatActivity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                ...
    
                getSupportActionBar().setHomeButtonEnabled(true);
            }
        }
    

    on AndroidManifest.xml:

    
                
            
    

    and finally, the action button on my menu (actionbar):

    public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()){
                ...
    
                case android.R.id.home:
                    NavUtils.navigateUpFromSameTask(this);
                    return true;
    
            }
    
            return super.onOptionsItemSelected(item);
    
        }
    

    Using NavUtils.navigateUpFromSameTask(this); worked for me, instead of finish().

提交回复
热议问题