Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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

like image 701
user6313452 Avatar asked May 14 '16 05:05

user6313452


People also ask

How do I put the back icon on my android toolbar?

AppCompatActivity just use: Toolbar toolbar = findViewById(R. id. toolbar); setSupportActionBar(toolbar); getSupportActionBar().

How can I customize my action bar in android?

This example demonstrate about how to create a custom action bar in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I get rid of the back arrow on my android toolbar?

getActionBar(). setDisplayShowHomeEnabled(false); //disable back button getActionBar(). setHomeButtonEnabled(false); In a older android phone, the back button is removed with these two code lines.


1 Answers

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:

public class MyPrefsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();

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

    }

    @Override
    public boolean onSupportNavigateUp(){
        finish();
        return true;
    }

    public static class MyPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}

Put the activity in your AndroidManifest.XML:

<activity android: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 = new Intent(activity, MyPrefsActivity.class);
activity.startActivity(prefsIntent);
like image 188
Baldeep Avatar answered Sep 23 '22 12:09

Baldeep