Как добавить ToolBar в PreferenceActivity?

Я хочу добавить ToolBar в PreferenceActivity в приложение для Android. Я написал следующий код.

  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();
        }
    });

}

Это отлично работало в моем API-интерфейсе телефона Android Kitkat, но принудительно закрылось в уровне API 10, т.е. gingerbread. Пожалуйста, предложите мне.

Ответ 1

Вам нужен макет, содержащий Toolbar и ListView с android: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;
    }
    ...
}

Посмотрите мой полностью рабочий пример:

Ссылка от команды Android: AppCompatPreferenceActivity

Ответ 2

Try:

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>

Ответ 3

Вы можете легко добавить панель инструментов из @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>

В v14/styles.xml для поддержки Back API

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

Ответ 4

Очень легко и хорошо работает в моем случае, раздувая пользовательскую панель инструментов.  В коде 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>

и в папке папок компоновки компоновки,

   <?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" />

Ответ 5

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

}

Ответ 6

Вместо:

public class PreferencesActivity extends Activity

Сделайте это:

public class PreferencesActivity extends AppCompatActivity