[android] Material Design - Material Toolbar In PreferenceActivity
Note: Only for Android versions after Gingerbread
After adding Toolbar to normal Activity I'm going to show you how you can implement Toolbar into settings.
First you need to create Toolbar XML file.
/* layout/toolbar_settings.xml */
<?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/settings_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
app:navigationIcon="?attr/homeAsUpIndicator"
app:title="Settings" />
And this is how java file may look to get Toolbar working.
/* java/[project]/SettingsActivity.java */
...
@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.toolbar_settings, root, false);
root.addView(bar, 0); // insert at top
bar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
setupSimplePreferencesScreen();
}
...
This code do not set Toolbar as ActionBar but it work as a regular View component. It adds Toolbar at top of layout and on back button click it stops entire Activity.
Written by Ondřej Page Bárta
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Tags
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#