除了一件事,我的 PreferenceActivity 工作得很好。 ActionBar 图标可以完美地将用户返回到我所有其他 Activity 中的上一个 Activity ,但在 PreferenceActivity 中不起作用。当我单击该图标时,它会闪烁,就好像它要返回到上一个 Activity 一样,但 PreferenceActivity 留在屏幕上。有趣的是,后退按钮确实使用户返回到之前的 Activity 。有没有办法让 ActionBar 的主页图标在 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 与我的其他 Activity 不同,因为 Home 按钮返回到 calling Activity 而不是 MainActivity。因此,解决方案需要(1)使用 startActivityForResult(而不是 startActivity)来调用 PreferenceActivity 和(2)在 PreferenceActivity 中使用 onOptionsItemSelected 来管理返回(根据@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;
}
关于android - PreferenceActivity 操作栏主页图标不会返回主页(与 ET :) 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15172111/