Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use addPreferencesFromResource for android 2.X?

Followed several howto but I can't understand,
how to use addPreferencesFromResource(R.xml.preferences) because is deprecated.

The best way is to use the fragment but fragments are available only later 3.0, I need to do for android version 2.x

Which way I'll follow?

like image 377
Pol Hallen Avatar asked Nov 19 '12 13:11

Pol Hallen


1 Answers

In Android, "deprecated" means "we have another solution that we think that you should consider". Particularly, for situations like this, you have no choice but to use addPreferencesFromResource() on Android 2.x, as onBuildHeaders() (the approach used in API Level 11+) does not exist.

You can create code that supports both:

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);
  }
}

Here, we use onBuildHeaders() for API Level 11+ and addPreferencesFromResource() on API Level 10 and below. Here is the complete sample project from which this code was pulled.

like image 157
CommonsWare Avatar answered Nov 01 '22 15:11

CommonsWare