我的偏好活动除了一件事情外,还是有效的.在所有其他活动中完美地将用户返回给先前活动的ActionBar图标在PreferenceActivity中不起作用.当我点击图标时,它将闪烁,就像它将返回到上一个活动,但是PreferenceActivity保持在屏幕上.有趣的是,后退按钮确实会将用户返回到上一个活动.有没有办法使ActionBar的Home图标在“PreferenceActivity”中正常工作?
这是代码:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set actionBar controls for Settings TextView actionBarTitle = (TextView) findViewById(Resources.getSystem().getIdentifier("action_bar_title","id","android")); ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setIcon(R.drawable.ic_launcher); actionBar.setDisplayShowTitleEnabled(true); actionBarTitle.setTextColor(Color.WHITE); actionBarTitle.setTextSize(16); actionBar.setTitle(R.string.settings_menu_title); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //Build.VERSION_CODES.ICE_CREAM_SANDWICH actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); // show back arrow on title icon actionBar.setDisplayShowHomeEnabled(true); } ...... Handle prefs (all working fine)..... }
}
//////呼叫代码////////
//Use menu button to access settings screen @Override public boolean onKeyDown(int keycode,KeyEvent e) { switch(keycode) { case KeyEvent.KEYCODE_MENU: Intent intent = new Intent(this,SettingsActivity.class); startActivity(intent); return true; } return super.onKeyDown(keycode,e); } // [END onKeyDown (for menu click capture) ]
解决方法
感谢@Axarydax指出我正确的方向.我意识到PreferenceActivity与我的其他活动不同,因为Home按钮返回到调用Activity而不是MainActivity.因此,解决方案需要(1)使用startActivityForResult(而不是startActivity)调用PreferenceActivity,(2)使用PreferenceActivity中的onOptionsItemSelected来管理返回值(per @ Axarydax的答案). (1)和(2)如下所示:
// (1) Menu button used to access PreferenceActivity @Override public boolean onKeyDown(int keycode,KeyEvent e) { switch(keycode) { case KeyEvent.KEYCODE_MENU: Intent intent = new Intent(this,SettingsActivity.class); startActivityForResult(intent,1); //enables return to here return true; } return super.onKeyDown(keycode,e); } // (2) Return to calling activity from PreferenceActivity @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { int SUCCESS_RESULT=1; setResult(SUCCESS_RESULT,new Intent()); finish(); //return to caller return true; } return false; }