add action bar with back button in preference activity

user6313452 picture user6313452 · May 14, 2016 · Viewed 11.1k times · Source

Here is my preference activity:

package com.example.hms.test;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class PrefsActivity extends PreferenceActivity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
    }

}

here I want to show an actionbar with name settings and a back button to home

Answer

Pooya picture Pooya · May 14, 2016

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:

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

    <activity
      android:name=".PrefsActivity"
      android:label="@string/title_activity_settings"
      android:parentActivityName=".MainActivity">
      <meta-data
        android: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:

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