Search code examples
androidandroid-fragmentspreferenceactivitymaterial-design

PreferenceFragment not shown when using ActionBarActivity


I have a PreferenceFragment and it can be shown inside an Activity. However, when I switch the Activity to an ActionBarActivity, the fragment is not shown. (I can only see an action bar and a blank white screen below.) The theme I am using is Theme.AppCompat.Light, therefore I need to use ActionBarActivity in order to display the ActionBar.

Here is my original code:

public class SettingsActivity extends Activity { // later changed to extend ActionBarActivity    

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

        // Display the fragment as the main content
        getFragmentManager().beginTransaction().
                replace(android.R.id.content, new SettingsFragment()).commit();
    }
}

Solution

  • I'm extending ActionBarActivity and my PreferenceFragment works.

    I think you need to call setContentView() on your Activity, to have an activity layout in which the fragment will be loaded.

    activity_preference_layout.xml

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="your.package.SettingsActivity">
    
        <include layout="@layout/toolbar"/>
    
        <FrameLayout
            android:id="@+id/preference_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
        </FrameLayout>
    </LinearLayout>
    

    Then your Activity should be something like:

    public class SettingsActivity extends ActionBarActivity {    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_preference_layout);
    
            getFragmentManager().beginTransaction().
                    replace(R.id.preference_container, new SettingsFragment()).commit();
        }
    }
    

    Note that I've replaced android.R.id.content with R.id.preference_container, which is the frame defined in the layout above.