Preferences screen using ActionBar Sherlock

onBuildHeaders() will only be called if you are running on API Level 11 or higher. On older devices, you are back to the classic addPreferencesFromResource() approach.

See this sample project for an example of supporting PreferenceFragment on API Level 11+ and classic preferences on older versions of Android.

Specifically, its SherlockFragmentActivity looks like:

package com.commonsware.android.preffragsbc;

import java.util.List;
import android.os.Build;
import android.os.Bundle;
import com.actionbarsherlock.app.SherlockPreferenceActivity;

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

    if (Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB) {
      addPreferencesFromResource(R.xml.preferences);
      addPreferencesFromResource(R.xml.preferences2);
    }
  }

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

In onCreate() we need to only do addPreferencesFromResource() if we are on an older device. In this case, my sample has two preference headers, and therefore two preference XML files, so we call addPreferencesFromResource() on both of them. On newer devices, onCreate() does nothing but chain to the superclass, which will trigger the call to onBuildHeaders().

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)