Toolbar in PreferenceActivity

December 12, 2014

Toolbar in PreferenceActivity

After scouring the internet, I think here is the way to display the Toolbar on PreferenceActivity.

Declare a preference activity layout, activity_settings.xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/settings_toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        app:navigationContentDescription="@string/abc_action_bar_up_description"
        android:background="?attr/colorPrimary"
        app:navigationIcon="?attr/homeAsUpIndicator"
        app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

In your PreferenceActivity, refer to the Toolbar.

public class SettingsActivity extends PreferenceActivity {

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

        setContentView(R.layout.activity_settings);

        Toolbar toolbar = (Toolbar) findViewById(R.id.settings_toolbar);
        toolbar.setTitle(R.string.title_settings);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //
        addPreferencesFromResource(R.xml.pref_settings);        
    }
}