When I converted an activity into PreferenceActivity
, I noticed that its ActionBar disappeared. I’ll show you how I brought the ActionBar back to my PreferenceActivity
.
In this guide I will assume that the name of the file that contains your is SettingsActivity.java
, and that the view assigned to your SettingsActivity.java
is named .
First, create settings_toolbar.xml
under /app/src/main/res/layout/
and place the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" app:navigationContentDescription="@string/abc_action_bar_up_description" android:background="?attr/colorPrimary" app:navigationIcon="?attr/homeAsUpIndicator" app:title="@string/action_settings" /> |
Then add the following overridden method to SettingsActivity.java
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent(); Toolbar bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false); root.addView(bar, 0); // insert at top bar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } |
The Java method programmatically creates a Toolbar object from the XML toolbar at settings_toolbar.xml
.
Reference(s): Creating a Preference Screen with support (v21) Toolbar