如何在PreferenceActivity中添加ToolBar?

我想在我的Android应用程序PreferenceActivity中添加ToolBar 。 我写了下面的代码。

  public class SettingsActivity extends PreferenceActivity { SendSMS sms; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent(); android.support.v7.widget.Toolbar bar = (android.support.v7.widget.Toolbar) LayoutInflater.from(this).inflate(R.layout.action_bar_setting, root, false); root.addView(bar, 0); bar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); 

}

这在我的Android Kitkat手机API 19完美工作,但强制closures在API级别10即姜饼 。 请build议我。

Solutions Collecting From Web of "如何在PreferenceActivity中添加ToolBar?"

你需要一个包含一个Toolbar和一个ListViewandroid:id="@android:id/list"

activity_settings.xml

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@id/content_frame" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.Toolbar android:id="@id/toolbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" /> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> 

SettingsActivity.java

 public class SettingsActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); addPreferencesFromResource(R.xml.preferences); ... } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } private void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } ... } 

看看我的完整工作示例:

  • activity_settings.xml
  • SettingsActivity.java

来自Android团队的参考: AppCompatPreferenceActivity

尝试:

 public class SettingsActivity extends AppCompatPreferenceActivity { ..... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); /* getFragmentManager().beginTransaction() .replace(android.R.id.content, new GeneralPreferenceFragment()) .commit(); */ //addPreferencesFromResource(R.xml.pref_general); } private void setupActionBar() { ViewGroup rootView = (ViewGroup)findViewById(R.id.action_bar_root); //id from appcompat if (rootView != null) { View view = getLayoutInflater().inflate(R.layout.app_bar_layout, rootView, false); rootView.addView(view, 0); Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); } } 

app_bar_layout.xml

 <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay"/> </android.support.design.widget.AppBarLayout> 

您可以轻松地从@android:style/Theme.Material.Light.DarkActionBar添加工具栏

AndroidManifest.xml中

 <activity android:name=".activity.SettingsActivity" android:theme="@style/SettingsTheme" android:label="Settings"/> 

v21 / styles.xml中

 <style name="SettingsTheme" parent="@android:style/Theme.Material.Light.DarkActionBar"> <item name="android:colorPrimary">@color/colorPrimary</item> <item name="android:colorPrimaryDark">@color/colorPrimaryDark</item> 

用于Back API支持的v14 / styles.xml

 <style name="SettingsTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar"> <item name="android:actionBarStyle">@style/ActionBar.V14.Movie.NoTitle</item> 

XML

  <PreferenceScreen xmlns:android ="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title = "@string/pref_cat_theme_title"> <SwitchPreference android:defaultValue = "false" android:key = "@string/pref_key_theme_dark" android:summary = "@string/text_disabled" android:title = "@string/pref_key_theme_title" /> <ListPreference android:defaultValue = "@string/pref_key_text_style_default" android:dialogTitle = "@string/pref_key_text_style_title" android:entries = "@array/pref_key_text_style_options" android:entryValues = "@array/pref_key_text_style_options" android:key = "@string/pref_key_text_style" android:summary = "@string/pref_key_text_style_default" android:title = "@string/pref_key_text_style_title" /> <ListPreference android:defaultValue = "@string/pref_key_text_size_default" android:dialogTitle = "@string/pref_key_text_size_title" android:entries = "@array/pref_key_text_size_options" android:entryValues = "@array/pref_key_text_size_options" android:key = "@string/pref_key_text_size" android:summary = "@string/pref_key_text_size_default" android:title = "@string/pref_key_text_size_title" /> </PreferenceCategory> <PreferenceCategory android:title = "@string/pref_cat_reminder_title"> <SwitchPreference android:defaultValue = "false" android:enabled = "false" android:key = "@string/pref_key_reminder" android:summary = "@string/text_disabled" android:title = "@string/pref_key_reminder_title" /> <RingtonePreference android:defaultValue = "content://settings/system/notification_sound" android:dependency = "@string/pref_key_reminder" android:key = "@string/pref_key_reminder_tone" android:ringtoneType = "notification" android:summary = "@string/text_disabled" android:title = "@string/pref_key_reminder_tone_title" /> <SwitchPreference android:defaultValue = "false" android:dependency = "@string/pref_key_reminder" android:key = "@string/pref_key_reminder_vibrate" android:summary = "@string/text_disabled" android:title = "@string/pref_key_reminder_vibrate_title" /> </PreferenceCategory> <PreferenceCategory android:title = "@string/pref_cat_about_title"> <Preference android:key = "@string/pref_key_changelog" android:summary = "@string/pref_key_changelog_summary" android:title = "@string/pref_header_change_log"> <intent android:action = "android.intent.action.VIEW" android:data = "https://play.google.com/store/apps/details?" /> </Preference> <Preference android:key = "@string/pref_key_rate" android:summary = "@string/pref_key_rate_summary" android:title = "@string/pref_key_rate_title"> <intent android:action = "android.intent.action.VIEW" android:data = "https://play.google.com/store/apps/details?" /> </Preference> <Preference android:key = "@string/pref_key_feedback" android:summary = "@string/pref_key_feedback_summary" android:title = "@string/pref_key_feedback_title"> <intent android:action = "android.intent.action.VIEW" android:data = "@string/mail_to_email"> <extra android:name = "android.intent.extra.SUBJECT" android:value = "@string/feedback_email_subject" /> </intent> </Preference> <Preference android:key = "@string/pref_key_more_apps" android:summary = "@string/pref_key_more_apps_summary" android:title = "@string/pref_key_more_apps_title"> <intent android:action = "android.intent.action.VIEW" android:data = "https://play.google.com/store/search?" /> </Preference> </PreferenceCategory> 

java代码是,

  public class ActivitySettings extends PreferenceActivity { private static final String TAG = "SB_ActivitySettings"; private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace( android.R.id.content, new ActivitySettings.AboutPreferenceFragment()).commit(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) || AboutPreferenceFragment.class.getName().equals(fragmentName); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { if (!super.onMenuItemSelected(featureId, item)) { NavUtils.navigateUpFromSameTask(this); } return true; } return super.onMenuItemSelected(featureId, item); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } @NonNull @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class AboutPreferenceFragment extends PreferenceFragment { private final PreferenceListener mListener = new PreferenceListener(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences_list); String keyList[] = getResources().getStringArray(R.array.pref_key_list); Preference preference; String value; for (String pref_key : keyList) { preference = findPreference(pref_key); if (preference != null) { if (preference instanceof ListPreference) { value = ((ListPreference) preference).getValue(); } else if (preference instanceof SwitchPreference) { value = ((SwitchPreference) preference).isChecked() ? "Disabled" : "Enabled"; } else if (preference instanceof RingtonePreference) { value = ((RingtonePreference) preference).getShowSilent() ? "Enabled" : "Silent"; } else { value = ""; } preference.setSummary(value); preference.setOnPreferenceChangeListener(mListener); preference.setOnPreferenceClickListener(mListener); } } } private void showChangeLogDialog() { Utilities.log(TAG, "showChangeLogDialog"); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); WebView webView = new WebView(getActivity()); webView.loadUrl("file:///android_asset/vinoj.html"); builder.setView(webView); builder.setNegativeButton(null, null); builder.setPositiveButton(null, null); builder.show(); } private class PreferenceListener implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener { @Override public boolean onPreferenceChange(Preference pPreference, Object pObject) { Utilities.log(TAG, "onPreferenceChange: " + pPreference.getKey()); String value; if (pPreference instanceof ListPreference) { value = pObject.toString(); } else if (pPreference instanceof SwitchPreference) { value = ((SwitchPreference) pPreference).isChecked() ? "Disabled" : "Enabled"; } else if (pPreference instanceof RingtonePreference) { value = ((RingtonePreference) pPreference).getShowSilent() ? "Enabled" : "Silent"; } else { value = pObject.toString(); } pPreference.setSummary(value); if (pPreference.getKey().equalsIgnoreCase( getString(R.string.pref_key_theme_dark))) { Utilities.restartApplication(getActivity()); } return true; } @Override public boolean onPreferenceClick(Preference pPreference) { String key = pPreference.getKey(); if (key == null) { Utilities.log(TAG, "onPreferenceClick() returning : key = null"); return false; } Utilities.log(TAG, "onPreferenceClick() called key = [" + key + "]"); if (key.equalsIgnoreCase(getString(R.string.pref_key_changelog))) { showChangeLogDialog(); } return true; } } } 

}

代替:

 public class PreferencesActivity extends Activity 

做这个:

 public class PreferencesActivity extends AppCompatActivity 

通过膨胀自定义工具栏非常简单,在我的情况下工作得很好。 在你的java代码中做如下,

  public class SettingsPrefActivity extends AppCompatPreferenceActivity { // private static final String TAG = SettingsPrefActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setting up toolbar getLayoutInflater().inflate(R.layout.toolbar_setting, (ViewGroup) findViewById(android.R.id.content)); Toolbar toolbar = findViewById(R.id.toolbar); toolbar.setTitle("Settings"); setSupportActionBars(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // load settings fragment getFragmentManager().beginTransaction().replace(android.R.id.content, new MainPreferenceFragment()).commit(); } } 

并在您的XML代码,在顶部添加一个首选项类别如下,

  <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> //put below line at the top of your xml preference layout screen.. <PreferenceCategory android:layout="@layout/toolbar_setting"></PreferenceCategory> 

并在您的布局资源文件夹toolbar_setting中,

  <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:elevation="@dimen/appbar_elevation" android:minHeight="?attr/actionBarSize" android:popupTheme="@style/ThemeOverlay.AppCompat.Light" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />