Android:使用图标作为后退按钮而不重新加载以前的活动

Jho*_*rra 10 android android-intent android-activity

我有以下代码,以启用主页按钮作为后退按钮.我面临的问题是来自这个活动,如果我使用真正的后退按钮它就像我离开它时简单地回到之前的活动.如果我使用主页按钮,它正在重新加载页面,所以我失去了以前对它做的事情.我确信这很简单,我很想念.

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.census_management_search, menu);
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    // Handle item selection
    switch (item.getItemId()) 
    {
        case android.R.id.home:
            Intent intent = new Intent(this, CensusManagementActivity.class);
            NavUtils.navigateUpTo(this, intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

vas*_*art 15

相反的Intent,并NavUtils尝试使用onBackPressed()方法.

@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    // Handle item selection
    switch (item.getItemId()) 
    {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 最好调用[`onBackPressed()`](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/app/Activity .java#Activity.onBackPressed%28%29)因为它检查片段的后台堆栈,如果它是空的,则调用`finish()` (2认同)