Skip to content Skip to sidebar Skip to footer

Add Action Bar With Back Button In Preference Activity

Here is my preference activity: package com.example.hms.test; import android.os.Bundle; import android.preference.PreferenceActivity; public class PrefsActivity extends Preferenc

Solution 1:

You should do couple of things:

  1. Add the following to your onCreate of PreferenceActivity:

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
  2. Override onOptionsItemSelected in PreferenceActivity:

    @OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
         switch (item.getItemId())
         {
             case android.R.id.home:
                 NavUtils.navigateUpFromSameTask(this);
                 returntrue;
         }
         returnsuper.onOptionsItemSelected(item);
     }
    
  3. change the <activity> tag in manifest for your PreferenceActivity to look something like this:

    <activityandroid:name=".PrefsActivity"android:label="@string/title_activity_settings"android:parentActivityName=".MainActivity"><meta-dataandroid:name="android.support.PARENT_ACTIVITY"android:value="com.example.android.MainActivity" /></activity>
  4. Finally put android:launchMode="singleTop" in your MainActivity <activity> tag in manifest:

    <activityandroid:name=".MainActivity"android:label="@string/app_name"android:launchMode="singleTop"android:theme="@style/AppTheme.NoActionBar"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

Solution 2:

The answer Pooya gave won't work for a PreferenceActivity. Instead make your class extend AppCompatActivity, and use a PreferenceFragment to load up the preference. Here is my code for settings:

publicclassMyPrefsActivityextendsAppCompatActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, newMyPreferenceFragment()).commit();

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @OverridepublicbooleanonSupportNavigateUp(){
        finish();
        returntrue;
    }

    publicstaticclassMyPreferenceFragmentextendsPreferenceFragment {
        @OverridepublicvoidonCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}

Put the activity in your AndroidManifest.XML:

<activityandroid:name=".MyPrefsActivity"android:label="Preferences"android:theme="@style/AppTheme"/>

And now you can start the settings activity using an intent in my Main Activity (or whichever parent activity you have) as normal:

Intent prefsIntent = newIntent(activity, MyPrefsActivity.class);
activity.startActivity(prefsIntent);

Solution 3:

I needed different action bar menu items in my activities so I created my MainActivity with a singleTop launchMode. That was great for getting my child activity's action bar set up, but it left my preferences activity without an action bar.

In the end, the key was in making sure the MainActivity theme had a parent of Theme.AppCompat.Light.NoActionBar:

<activityandroid:name=".MainActivity"android:label="@string/app_name"android:launchMode="singleTop"android:theme="@style/AppTheme"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity>

and the SettingsActivity theme had the parent Theme.AppCompat.Light.DarkActionBar:

<activityandroid:name=".SettingsActivity"android:label="@string/title_activity_settings"android:theme="@style/SettingsTheme"android:parentActivityName=".MainActivity"><meta-dataandroid:name="android.support.PARENT_ACTIVITY"android:value="net.deatrich.app.bodyandminddbt.MainActivity" /></activity>

In styles.xml

<stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark">@color/colorPrimaryDark</item><itemname="colorAccent">@color/colorAccent</item><itemname="windowActionBar">false</item><itemname="windowNoTitle">true</item></style><stylename="SettingsTheme"parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark">@color/colorPrimaryDark</item><itemname="colorAccent">@color/colorAccent</item></style>

There's probably a better way to style it but this works.

For anyone else reading, also remember to derive your SettingsActivity from AppCompatPreferenceActivity:

SettingsActivity.java:

publicclassSettingsActivityextendsAppCompatPreferenceActivity {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // I'm displaying a fragment as the main content.
    getFragmentManager().beginTransaction()
            .replace(android.R.id.content, newGeneralPreferenceFragment())
            .commit();

    setupActionBar();

}


privatevoidsetupActionBar() {

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);


}

@OverridepublicbooleanonMenuItemSelected(int featureId, MenuItem item) {
    intid= item.getItemId();
    if (id == android.R.id.home) {
        if (!super.onMenuItemSelected(featureId, item)) {
            NavUtils.navigateUpFromSameTask(this);
        }
        returntrue;
    }
    returnsuper.onMenuItemSelected(featureId, item);
}
...

Solution 4:

okay. now you still trouble then i have unique solution for you which work 100% with just minor changes.

so first of all create one style for only settings activity.

here is my toolbar styles code.

<stylename="Toolbar_settings_style"parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark">@color/colorPrimaryDark</item><itemname="colorAccent">@color/colorAccent</item><itemname="android:colorControlNormal">@color/appTitleTextColor</item></style>

and here is my stlyes.xml looks like

<resources><!-- Base application theme. --><stylename="AppTheme"parent="Theme.AppCompat.Light.NoActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark">@color/colorPrimaryDark</item><itemname="colorAccent">@color/colorAccent</item><itemname="android:colorControlNormal">@color/appTitleTextColor</item></style><stylename="AppTheme.NoActionBar"><itemname="windowActionBar">false</item><itemname="windowNoTitle">true</item></style><stylename="AppTheme.AppBarOverlay"parent="ThemeOverlay.AppCompat.Dark.ActionBar" /><stylename="AppTheme.PopupOverlay"parent="ThemeOverlay.AppCompat.Light" /><stylename="Toolbar_settings_style"parent="Theme.AppCompat.Light.DarkActionBar"><!-- Customize your theme here. --><itemname="colorPrimary">@color/colorPrimary</item><itemname="colorPrimaryDark">@color/colorPrimaryDark</item><itemname="colorAccent">@color/colorAccent</item><itemname="android:colorControlNormal">@color/appTitleTextColor</item></style></resources>

yes. you noticed i have create duplicate styles(appTheme and Toolbar_settings_style both are same styles attribute) for only settingsActivity. it is very important to create duplicate styles.

Now go to your settingsActivity and paste below code inside onCreate().

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

After placing above code now my SettingsActivity looks like

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;


import settingspreferences.AppCompatPreferenceActivity;

publicclassUser_SettingsextendsAppCompatPreferenceActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // load settings fragment
        getFragmentManager().beginTransaction().replace(android.R.id.content, newMainPreferenceFragment()).commit();
    }

    publicstaticclassMainPreferenceFragmentextendsPreferenceFragment {
        @OverridepublicvoidonCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);

            // gallery EditText change listener
            bindPreferenceSummaryToValue(findPreference(getString(R.string.key_gallery_name)));

            // notification preference change listener

        }

        @OverridepublicbooleanonOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == android.R.id.home) {
             //   onBackPressed();
            }
            returnsuper.onOptionsItemSelected(item);
        }

        privatestaticvoidbindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

            sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                    PreferenceManager
                            .getDefaultSharedPreferences(preference.getContext())
                            .getString(preference.getKey(), ""));
        }

        /**
         * A preference value change listener that updates the preference's summary
         * to reflect its new value.
         */privatestatic Preference.OnPreferenceChangeListenersBindPreferenceSummaryToValueListener=newPreference.OnPreferenceChangeListener() {
            @OverridepublicbooleanonPreferenceChange(Preference preference, Object newValue) {
                StringstringValue= newValue.toString();

                if (preference instanceof ListPreference) {
                    // For list preferences, look up the correct display value in// the preference's 'entries' list.ListPreferencelistPreference= (ListPreference) preference;
                    intindex= listPreference.findIndexOfValue(stringValue);

                    // Set the summary to reflect the new value.
                    preference.setSummary(
                            index >= 0
                                    ? listPreference.getEntries()[index]
                                    : null);

                } elseif (preference instanceof RingtonePreference) {
                    // For ringtone preferences, look up the correct display value// using RingtoneManager.if (TextUtils.isEmpty(stringValue)) {
                        // Empty values correspond to 'silent' (no ringtone).
                        preference.setSummary(R.string.pref_ringtone_silent);

                    } else {
                        Ringtoneringtone= RingtoneManager.getRingtone(
                                preference.getContext(), Uri.parse(stringValue));

                        if (ringtone == null) {
                            // Clear the summary if there was a lookup error.//  preference.setSummary(R.string.summary_choose_ringtone);
                        } else {
                            // Set the summary to reflect the new ringtone display// name.Stringname= ringtone.getTitle(preference.getContext());
                            preference.setSummary(name);
                        }
                    }

                } elseif (preference instanceof EditTextPreference) {
                    if (preference.getKey().equals("key_gallery_name")) {
                        // update the changed gallery name to summary filed
                        preference.setSummary(stringValue);
                    }
                } else {
                    preference.setSummary(stringValue);
                }
                returntrue;
            }
        };
    }

}

Now let's come to real important part. go to manifest.xml file and find your settingsActivity and paste below code.

<activityandroid:name=".User_Settings"android:theme="@style/Toolbar_settings_style"></activity>

so here is my AndroidManifest.xml looks like

<?xml version="1.0" encoding="utf-8"?><manifestxmlns:android="http://schemas.android.com/apk/res/android"package="mypackage"><uses-permissionandroid:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><!--  --><activityandroid:name=".MainActivity"android:windowSoftInputMode="adjustPan"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter><!-- <intent-filter> --><!-- <action android:name="android.intent.action.SEARCH" /> --><!-- </intent-filter> --><meta-dataandroid:name="android.app.searchable"android:resource="@xml/searchable" /></activity><activityandroid:name=".Add_Items" /><activityandroid:name=".Product_details_view" /><activityandroid:name=".editProducts"android:parentActivityName=".Product_details_view" /><activityandroid:name=".User_Settings"android:theme="@style/Toolbar_settings_style"></activity></application></manifest>

This is all you need to shows Toolbar on settingsActivity.

Post a Comment for "Add Action Bar With Back Button In Preference Activity"