简体   繁体   中英

Android PreferenceActivity without XML

Is there a way to create Holo-styled (non-deprecated) PreferenceActivity and it's headers/fragments in pure Java, not XML? Is it possible to add and remove headers programmatically?

Is there a way to create Holo-styled (non-deprecated) PreferenceActivity and it's headers/fragments in pure Java, not XML?

Your onBuildHeaders() method can presumably create PreferenceActivity.Header objects by other means. You might want to create a test project that does headers via XML and dump the contents of the resulting Header object(s) to confirm that you will populate yours correctly, since the documentation for Header is a bit terse.

Is it possible to add and remove headers programmatically?

There is an invalidateHeaders() method on PreferenceActivity that looks promising. Through examining the source code, it looks like calling that will trigger another call to onBuildHeaders() , where you would provide the new list, much like invalidateOptionsMenu() triggers a call to onCreateOptionsMenu() .

You can create/add your own Headers in OnBuildHeaders, and then check ids in onHeaderClick:

@Override
public void onBuildHeaders(List<Header> target) {
    //loadHeadersFromResource(R.xml.prefs_sync_plugins, target);

    Header customHeader = new Header();
    customHeader.titleRes= R.string.customHeaderTitle;
    customHeader.id = R.string.customHeaderTitle;
    target.add(customHeader);
}

@Override
public void onHeaderClick(Header header, int position) {
    if (header.id == R.string.customHeaderTitle) {
        // Do something
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM