Toolbar in a settings activity/fragment

时间:2016-04-04 17:49:23

标签: java android android-preferences

I have searched the web for solution to my problem and can't seem to find anything that will work. I have implemented the following into my app and it does work. However, I would like to to add a toolbar at the top with the left arrow to allow the user to go back. can anyone help me out with this.

public class ActivitySettings extends PreferenceActivity {

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

     public static class MyPreferenceFragment extends PreferenceFragment {

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

Thanks for any and all help.

2 个答案:

答案 0 :(得分:1)

This is the exact use case of the Preferences Support Library - it allows you to not use PreferenceActivity and instead use a PreferenceFragmentCompat. This allows you to use AppCompatActivity and the Toolbar support built into it.

答案 1 :(得分:0)

The PreferenceActivity doesn't extend the AppCompatActivity.

As solution you can use the PreferenceFragmentCompat with any Activity or AppCompatActivity

In this case you have to set preferenceTheme in your theme:

<style name="AppTheme" parent="@style/Theme.AppCompat.Light">
  ...
  <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>

In this way you can customize the preferenceTheme to style the layouts used for each preference.

Moreover with the new 22.1+ appcompat you can use the AppCompatDelegate to extend AppCompat's support to any Activity.

You can check this official link to AppCompatPreferenceActivity, where you can find an example of this technique.