Android - Headers categories in PreferenceActivity with PreferenceFragment

扶醉桌前 提交于 2019-12-03 08:42:38

Maybe first header is default selected menu. If so, it should have fragment attribute to show it right side.

As bestofbest1 said, the problem was that Android tried to show the first element in the preferences_headers.xml, which did not contain a fragment.

To fix it, I added in MainPreferenceActivity's onCreate the line below (BEFORE super.onCreate) to select a default fragment when using a tablet :

if(onIsMultiPane()) getIntent().putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, PreferencesFragment.class.getName());

I also set a default fragment in PreferencesFragment :

String settings = "DIVE";
if(getArguments() != null) settings = getArguments().getString("settings");

Then a last problem, PreferenceActivity.EXTRA_SHOW_FRAGMENT does not select the header in the left side. To fix it in MainPreferencesActivity save a reference to your headers (in onBuildHeaders), and add :

@Override
protected void onResume() {

    // Call super :
    super.onResume();

    // Select the displayed fragment in the headers (when using a tablet) :
    // This should be done by Android, it is a bug fix
    if(_headers != null) {

        final String displayedFragment = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
        if (displayedFragment != null) {
            for (final Header header : _headers) {
                if (displayedFragment.equals(header.fragment)) {
                    switchToHeader(header);
                    break;
                }
            }
        }
    }
}

I had issues getting Tim's solution to work for me (the program would still crash). I worked around this in a different way by just selecting the first non-category header by default instead of the first in the list. To do this I overrided the method onGetInitialHeader in my PreferenceActivity

@Override
public Header onGetInitialHeader() {
    for (int i = 0; i < mHeaders.size(); i++) {
        Header h = mHeaders.get(i);
        if (!isCategory(h)) {
            return h;
        }
    }
}

protected static boolean isCategory(Header h) {
    return h.fragment == null;
}

mHeaders is just a reference to the header list saved in the call to onBuildHeaders. It should also be noted that this is only an issue pre 4.3, it has since been fixed. Hope this helps someone out

As a simpler form of Tim Autin's solution, disable multi-pane altogether to produce a single-pane, phone-like display on tablets.

public class PreferencesActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if(onIsMultiPane())
            getIntent().putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true);
        super.onCreate(savedInstanceState);
    }
...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!