Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

Tags:

android

xml

I just noticed the fact that the method addPreferencesFromResource(int preferencesResId) is marked deprecated in Android's documentation (Reference Entry).

Unfortunately, no alternative method is provided in the method's description.

Which method should be used instead in order to connect a preferenceScreen.xml to the matching PreferenceActivity?

like image 297
mweisz Avatar asked Jul 25 '11 21:07

mweisz


2 Answers

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

like image 128
glorifiedHacker Avatar answered Sep 28 '22 16:09

glorifiedHacker


To add more information to the correct answer above, after reading an example from Android-er I found you can easily convert your preference activity into a preference fragment. If you have the following activity:

public class MyPreferenceActivity extends PreferenceActivity {     @Override     protected void onCreate(final Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         addPreferencesFromResource(R.xml.my_preference_screen);     } } 

The only changes you have to make is to create an internal fragment class, move the addPreferencesFromResources() into the fragment, and invoke the fragment from the activity, like this:

public class MyPreferenceActivity extends PreferenceActivity {     @Override     protected void onCreate(final Bundle savedInstanceState)     {         super.onCreate(savedInstanceState);         getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();     }      public static class MyPreferenceFragment extends PreferenceFragment     {         @Override         public void onCreate(final Bundle savedInstanceState)         {             super.onCreate(savedInstanceState);             addPreferencesFromResource(R.xml.my_preference_screen);         }     } } 

There may be other subtleties to making more complex preferences from fragments; if so, I hope someone notes them here.

like image 36
Garret Wilson Avatar answered Sep 28 '22 17:09

Garret Wilson