36

Problem
Rotating a device from a one-pane portrait PreferenceScreen to a two-pane landscape PreferenceScreen, causes landscape to only show as one-pane. Does NOT occur when viewing the headers screen.

Setup
This is for ICS and up only. I have a PreferenceActivity which loads preference-headers. Each header links with a Fragment, which in turn loads a PreferenceScreen. Pretty run of the mil.

Details
Everything worked well until I noticed that Android will only auto-switch to a two-pane look for certain screens. After some research I learned from a Commonsware post that Android will only do so for sw720dp. Bit of a waste if you ask me since many devices def have plenty of room for two-panes. So I overrided the onIsMultiPane() method to return true for w600dp and up. Worked like a charm....kinda.

Given a device which will show single-pane in portrait and dual-pane in landscape; viewing the headers in portrait and rotating to landscape, works fine. However if one selects a header and loads it's subsequent screen in portrait mode, then rotate to landscape the device will stay single-pane instead of switching back to dual-pane. If you then back navigate to the headers screen, it'll return to a dual-pane look except that it won't pre-select a header. As a result the detailed pane stays blank.

Is this intended behavior? Anyway to work around it? I tried overriding onIsHidingHeaders() as well but that just caused everything to show a blank screen.

Code
Preference Activity:

public class SettingsActivity extends PreferenceActivity {
@Override
public void onBuildHeaders(List<Header> target) {
    super.onBuildHeaders(target);
    loadHeadersFromResource(R.xml.preference, target);
}

@Override
public boolean onIsMultiPane() {
    return getResources().getBoolean(R.bool.pref_prefer_dual_pane);
}
}


A Preference Header Frag:

public class ExpansionsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.pref_expansions);
}

public static ExpansionsFragment newInstance() {
    ExpansionsFragment frag = new ExpansionsFragment();

    return frag;
}
}
4

2 回答 2

2

问题已解决
随着这个问题变得如此受欢迎,我决定再次重新审视这个问题,看看我是否能找到解决方案......我做到了。找到了一个很好的解决方法,可以解决显示单窗格而不是双窗格的问题,并确保在双窗格模式下始终预先选择标题。

如果你不关心解释,你可以直接跳到代码。如果您不关心 ICS,可以删除很多标头跟踪代码,因为 JB 为标头数组列表添加了一个 getter。

双窗格问题
在单窗格模式或双窗格模式下查看首选项标题列表时,只会创建一个 PreferenceActivity,并且在两种情况下都是相同的活动。因此,在处理将切换窗格模式的屏幕旋转时从来没有问题。

但是,在单窗格模式下,当您单击标题时,相应的片段将附加到新的 PreferenceActivity。这个包含 PreferenceActivity 的新片段永远不会调用onBuildHeaders(). 为什么会这样?它不需要显示它们。这就是问题所在。

当将该片段旋转到双窗格模式时,它没有任何标题列表要显示,因此它只是继续仅显示片段。即使它确实显示了标题的列表,您也会遇到一些 backstack 问题,因为您现在将拥有两个显示标题的 PreferenceActivity 副本。继续点击足够多的标题,您将获得相当长的活动堆栈供用户浏览。结果,答案很简单。只是finish()活动。然后它将加载具有标题列表的原始 PreferenceActivity 并将正确显示双窗格模式。

自动选择页眉
下一个需要解决的问题是,使用新修复程序在单窗格模式和双窗格模式之间切换不会自动选择页眉。您只剩下一个标题列表,并且没有加载任何详细信息片段。这个修复并不那么简单。基本上,您只需要跟踪上次单击的标题并确保在 PreferenceActivity 创建期间...始终选择标题。

这最终在 ICS 中有点烦人,因为 API 没有为内部跟踪的标头列表公开 getter。Android 确实已经保留了该列表,您可以通过使用相同的私有存储的内部字符串键从技术上检索它,但这只是一个糟糕的设计选择。相反,我建议您自己手动再次持久化它。

如果您不关心 ICS,那么您可以只使用getHeaders()JB 中公开的方法,而不必担心任何保存/恢复状态的东西。

代码

public class SettingsActivity extends PreferenceActivity {
private static final String STATE_CUR_HEADER_POS = "Current Position";
private static final String STATE_HEADERS_LIST   = "Headers List";

private int mCurPos = AdapterView.INVALID_POSITION;  //Manually track selected header position for dual pane mode
private ArrayList<Header> mHeaders;  //Manually track headers so we can select one. Required to support ICS.  Otherwise JB exposes a getter instead.

@Override
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.preference, target);
    mHeaders = (ArrayList<Header>) target;  //Grab a ref of the headers list
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //This is the only code required for ensuring a dual pane mode shows after rotation of a single paned preference screen
    if (onIsMultiPane() && onIsHidingHeaders()) {
        finish();
    }
}

@Override
public boolean onIsMultiPane() {
    //Override this if you want dual pane to show up on smaller screens
    return getResources().getBoolean(R.bool.pref_prefer_dual_pane);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    //Intercept a header click event to record its position.
    mCurPos = position;
}

@Override
protected void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);

    //Retrieve our saved header list and last clicked position and ensure we switch to the proper header.
    mHeaders = state.getParcelableArrayList(STATE_HEADERS_LIST);
    mCurPos = state.getInt(STATE_CUR_HEADER_POS);
    if (mHeaders != null) {
        if (mCurPos != AdapterView.INVALID_POSITION) {
            switchToHeader(mHeaders.get(mCurPos));
        } else {
            switchToHeader(onGetInitialHeader());
        }
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Persist our list and last clicked position
    if (mHeaders != null && mHeaders.size() > 0) {
        outState.putInt(STATE_CUR_HEADER_POS, mCurPos);
        outState.putParcelableArrayList(STATE_HEADERS_LIST, mHeaders);
    }
}
}
于 2014-04-20T15:46:34.997 回答
0

下面代码背后的关键思想来自问题中链接的 Commonsware 博客条目,因此感觉很相关。我特别必须扩展这个概念来处理一个听起来与问题中的问题非常相似的方向变化问题,所以希望它能给你一个开始。

Settings 类不应该与方向问题有任何关系,但无论如何都要包括它以明确。

根据我的代码注释,看看checkNeedsResource调用onCreate是否有帮助:

public class SettingsActivity
extends 
    PreferenceActivity
{

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Show settings without headers for single pane or pre-Honeycomb. Make sure to check the
    // single pane or pre-Honeycomb condition again after orientation change.
    if (checkNeedsResource()) {
        MyApp app = (MyApp)getApplication();
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(app);
        Settings settings = new Settings();
        addPreferencesFromResource(R.xml.prefs_api);
        settings.setupPreference(findPreference(MyApp.KEY_USERNAME), prefs.getString(MyApp.KEY_USERNAME, null), true);
        settings.setupPreference(findPreference(MyApp.KEY_API_URL_ROOT), prefs.getString(MyApp.KEY_API_URL_ROOT, null), true);
        if (this.isHoneycomb) {
            // Do not delete this. We may yet have settings that only apply to Honeycomb or higher.
            //addPreferencesFromResource(R.xml.prefs_general);
        }
        addPreferencesFromResource(R.xml.prefs_about);
        settings.setupPreference(findPreference(MyApp.KEY_VERSION_NAME), app.getVersionName());
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onBuildHeaders(List<Header> target) {
    super.onBuildHeaders(target);

    // This check will enable showing settings without headers for single pane or pre-Honeycomb. 
    if (!checkNeedsResource()) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }
}

private boolean checkNeedsResource() {
    // This check will enable showing settings without headers for single pane or pre-Honeycomb. 
    return (!this.isHoneycomb || onIsHidingHeaders() || !onIsMultiPane());
}

private boolean isHoneycomb = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB);

}

public class Settings {

public Settings() {
}

public void setupPreference(Preference pref, String summary, boolean setChangeListener) {
    if (pref != null) {
        if (summary != null) {
            pref.setSummary(summary);
        }

        pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference pref, Object newValue) {
                pref.setSummary(newValue.toString());
                return true;
            }

        });
    }
}

public void setupPreference(Preference pref, String summary) {
    setupPreference(pref, summary, false);
}

}

于 2014-04-09T00:21:53.840 回答