2014-10-26 109 views
0

当我创建一个活动时,它会自动添加回操作栏中的主要活动选项。它看起来像那些是这样做的功能:操作栏中的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; 
} 

@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()时,它没有这样做,但我不知道如何在操作栏中使用它。

回答

2

这是简单,它完美的作品:

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); 
     } 
    } 
} 
0

试试这个

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