3

I created a single activity setting with a preferenceFragment with the following source:

package com.ocsaram.vdchorta;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;

public class SettingsActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    getFragmentManager().beginTransaction().replace(android.R.id.content,
            new SettingsFragment()).commit();
    assert getSupportActionBar() != null;
    PreferenceManager.setDefaultValues(this, R.xml.settings_preference, false);
}

public static class SettingsFragment extends PreferenceFragment {

   
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings_preference);
        super.onCreate(savedInstanceState);

        

    }
}

}

This is the file setting_preference.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <EditTextPreference
        android:key="sample_key"
        android:title="Title"
        android:inputType="number"
        android:summary="ciao"/>
    <EditTextPreference
        android:key="sample2_key"
        android:title="Title 2"
        android:inputType="number"
        android:summary="ciao"/>
</PreferenceScreen>

Now I would like to add an actionBar in the PreferenceFragment only that I'm not succeeding. Can anyone help me? Thanks in advance for the help. Greetings.

Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53
Mirko Marasco
  • 107
  • 2
  • 8
  • Related post - [How to add Action Bar from support library into PreferenceActivity?](https://stackoverflow.com/q/17849193/465053) – RBT Aug 14 '18 at 05:02

1 Answers1

0

In the onCreate() method, you can actually include the following snippet:

ActionBar actionBar = getActionBar();
if (actionBar != null) {
    // Show the Up button in the action bar.
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle("YourTitle");
}

This will automatically add the actionbar, which will also include the title as defined in .setTitle("YourTitle") as well as the 'back' button on the top left of the actionbar as defined by .setDisplayHomeAsUpEnabled(true).

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Syuqri
  • 86
  • 1
  • 6