Search code examples
androidandroid-preferences

Example off addPreferenceFromIntent in Android


Is there any example on addPreferenceFromIntent


Solution

  • Yes, I can give you a quick example,

    Step 1

    Create a PreferenceFragment and provide it with an Intent that identifies an Activity.

    The Activity will have some meta-data associated with it that the PreferenceFragment will use to create its layout.

    public class MyPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Intent intent = new Intent(getActivity(), MyActivityWithPreferences.class);
            addPreferencesFromIntent(intent);
        }
    }
    

    Step 2

    Now you need to create an activity MyActivityWithPreferences and add it to the manifest.xml file.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example"
        android:versionCode="1"
        android:versionName="1.0">
    
        <uses-sdk android:minSdkVersion="15" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name">
    
            <activity
                android:name="MyActivity"
                android:label="@string/app_name">
    
                <intent-filter>
    
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <activity android:name=".MyActivityWithPreferences">
    
                <meta-data
                    android:name="android.preference"
                    android:resource="@xml/preference_from_intent" />
            </activity>
        </application>
    </manifest> 
    

    Please notice the meta-data element as the child of the activity there which will use the specified resource for creating its layout.

    Step 3

    Here is an example of such a resource file which you can use to inflate the layout of your preference screen.

    <PreferenceScreen android:key="screen_preference"
                      android:title="Title Screen Preferences"
                      android:summary="Summary Screen Preferences">
    
      <CheckBoxPreference android:key="next_screen_checkbox_preference"
                          android:title="Next Screen Toggle Preference Title"
                          android:summary="Next Screen Toggle Preference Summary" />
    
    </PreferenceScreen>
    

    Hope it helps.