# Adding toolbar to Preference Activity

Published: 2015-11-11
Last updated: 2019-11-17

There are a lot of questions on StackOverflow about adding an ActionBar/Toolbar to the PreferenceActivity. However this task is quite easy in the newer versions of Android Studio.

I'm using Android Studio 1.4. When I create a new preference activity from the menu, Android Studio adds an extra abstract `AppCompatPreferenceActivity` class which extends PreferenceActivity. The `SettingsActivity` class I created from the menu extends the `AppCompatPreferenceActivity` class. This abstract class has a lot of useful methods that's missing in the PreferenceActivity class.

To add the toolbar, all I need to do is inflate the toolbar into the view and set it as the ActionBar by calling `setSupportActionBar()` or `setActionBar()` if you aren't using the AppCompat Toolbar.

Here's my `toolbar.xml`:

```markup

```

Adding the following lines of code at the beginning of the `setupActionBar()` will add the toolbar at runtime.

```java
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup)findViewById(android.R.id.content));
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

```

The toolbar now appears, but it overlaps the activity content:
![Screenshot](/images/2015/11/Screenshot_2015-11-11-12-35-31.png)

This can be fixed by adding a padding to the listview. The listview can be accessed using the `getListView()` of the `AppCompatPreferenceActivity`.

Adding the following code will fix the issue:

```java
int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) getResources().getDimension(R.dimen.activity_vertical_margin) + 30, getResources().getDisplayMetrics());
getListView().setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);

```

![Screenshot](/images/2015/11/Screenshot_2015-11-11-13-49-13.png)

If you can't use Android Studio 1.4 for some reason, you may refer to the complete code on the gist [here](https://gist.github.com/gldraphael/7ecd60525313275b56f9).

BTW, I've finally added comments to the blog. So yay!

