我找到了一种解决方法,可以在嵌套的PreferenceScreen上实际启用ActionBar主页按钮...但是它并没有在我的PreferenceActivity中调用OnOptionsItemSelected。有人知道在嵌套的PreferenceScreen上实际使用主页按钮的方法吗?
此处修改第35条:
http://code.google.com/p/android/issues/detail?id=4611
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference)
{
super.onPreferenceTreeClick(preferenceScreen, preference);
if (preference!=null)
if (preference instanceof PreferenceScreen)
if (((PreferenceScreen)preference).getDialog()!=null)
((PreferenceScreen)preference).getDialog().getActionBar().setHomeButtonEnabled(true);
return false;
}
答案 0 :(得分:46)
我最近遇到了这个问题,这就是我解决它的方法。首先访问PreferenceScreen我使用与上面提到的完全相同的方法。
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
super.onPreferenceTreeClick(preferenceScreen, preference);
// If the user has clicked on a preference screen, set up the action bar
if (preference instanceof PreferenceScreen) {
initializeActionBar((PreferenceScreen) preference);
}
return false;
}
从这里开始我研究了PreferenceScreen是什么,我很难过发现它只是一个Dialog的包装器。接下来,我设置操作栏显示选项并尝试找到主页按钮区域。遗憾的是,这并不容易获得,但在层次结构查看器的帮助下,我设法通过查找主页图标然后查看其父视图来获取访问权限。一旦我们有权访问包含的LinearLayout,我们就可以附加一个onClickListener来解除PreferenceScreen的对话框,该对话框调用PreferenceScreen's onDismissListener并将我们返回到上一个屏幕。
/** Sets up the action bar for an {@link PreferenceScreen} */
public static void initializeActionBar(PreferenceScreen preferenceScreen) {
final Dialog dialog = preferenceScreen.getDialog();
if (dialog != null) {
// Inialize the action bar
dialog.getActionBar().setDisplayHomeAsUpEnabled(true);
// Apply custom home button area click listener to close the PreferenceScreen because PreferenceScreens are dialogs which swallow
// events instead of passing to the activity
// Related Issue: https://code.google.com/p/android/issues/detail?id=4611
View homeBtn = dialog.findViewById(android.R.id.home);
if (homeBtn != null) {
OnClickListener dismissDialogClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
};
// Prepare yourselves for some hacky programming
ViewParent homeBtnContainer = homeBtn.getParent();
// The home button is an ImageView inside a FrameLayout
if (homeBtnContainer instanceof FrameLayout) {
ViewGroup containerParent = (ViewGroup) homeBtnContainer.getParent();
if (containerParent instanceof LinearLayout) {
// This view also contains the title text, set the whole view as clickable
((LinearLayout) containerParent).setOnClickListener(dismissDialogClickListener);
} else {
// Just set it on the home button
((FrameLayout) homeBtnContainer).setOnClickListener(dismissDialogClickListener);
}
} else {
// The 'If all else fails' default case
homeBtn.setOnClickListener(dismissDialogClickListener);
}
}
}
}