操作栏中的Android后退选项

操作栏中的Android后退选项,android,Android,当我创建一个活动时,它会自动在操作栏中添加一个返回主活动选项。看起来这些是实现这一点的函数: @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.app_settings, menu); return true; } @O

当我创建一个活动时,它会自动在操作栏中添加一个返回主活动选项。看起来这些是实现这一点的函数:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
} 

是否有方法使用finish()使其返回?现在看起来它重置了一些保存的值,我想保留它们。当我尝试使用finish()时,它没有做到这一点,但我不确定如何在操作栏中使用它。

这更简单,效果也更好:

public class BackButtonExample extends Activity {
    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.duahs);

        ActionBar bar = getActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0B4C5F")));
        bar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
试试这个

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                if(item.getItemId()==android.R.id.home  {
                       finish();
              return true;    }
           else{
                return super.onOptionsItemSelected(item);
               }
    }