Marco Zanetti
Marco Zanetti

Reputation: 4271

Empty PreferenceActivity though a PreferenceFragment was added

I'm stuck with a pretty simple issue: I'm trying to build a Preference screen in my app and I'd like to do it with the new, now-standard PreferenceFragment method.

This is my prefs xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory android:title="@string/prefs_interface_settings">

    <SwitchPreference
        android:key="show_average"
        android:title="Show average length of work day"
        android:defaultValue="false"
        android:summary="Display the calculated average in the app title" />

    <EditTextPreference
        android:key="edittext_preference"
        android:title="@string/workday_duration_prefs_title"
        android:summary="summary_edittext_preference"
        android:defaultValue="8"
        android:dialogTitle="dialog_title_edittext_preference" />

    </PreferenceCategory>
</PreferenceScreen>

This is my SettingsActivity

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.widget.Toast;


public class SettingsActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
    }
}

and - finally - this is my SettingsFragment:

import android.os.Bundle;
import android.preference.PreferenceFragment;


public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            addPreferencesFromResource(R.xml.app_preferences); //Gets settings from XML
        }
    }

}

When I run the application, if I do open said activity I get an empty one, just like the fragment was not initialized - or not shown - for some reason. But the code is so simple... I just can't get what I do wrong!

Thank you everybody for your help

Upvotes: 0

Views: 1008

Answers (1)

Anggrayudi H
Anggrayudi H

Reputation: 15155

getArguments() used only when you create <preference-headers/>. The arguments declared in <extra/> element of the preference-header XML file. Once you declared it, you will call this code within PreferenceFragment:

String settings = getArguments().getString("settings");
if (settings.equals("myArgument")) {
    addPreferencesFromResource(R.xml.settings_wifi);
}

But, as you do not use <preference-headers/>, so you only need to call this code in the PreferenceFragment:

addPreferencesFromResource(R.xml.app_preferences);

Upvotes: 1

Related Questions