设置Android PreferenceFragment的正确方法是什么? [英] What's the proper way to setup an Android PreferenceFragment?

查看:81
本文介绍了设置Android PreferenceFragment的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Android应用程序中实现基本设置活动,并且出现黑屏或崩溃.我看过的文档和样本对您没有帮助,因为它们太旧或不一致.例如,根据您的外观,设置活动应扩展活动 PreferenceActivity 或AppCompatPreferenceActivity(文件的一部分)新建>活动>设置活动).

I'm trying to implement a basic settings activity in an Android app and either get a blank white screen or a crash. The documentation and samples I've seen aren't helping because they're either old or inconsistent. For example, depending on where you look, the settings activity should either extend Activity, PreferenceActivity, or AppCompatPreferenceActivity (part of the File>New>Activity>Settings Activity).

developer.android.com说您应该实现以下目标:

developer.android.com says you should implement the following:

public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
    }
}

但是,在Android Studio中使用的设置活动"并未对其创建的三个片段中的任何一个进行此调用.它使用首选项标题.

Yet, the Settings Activity generated in Android Studio uses does not make this call for any of the three fragments it creates. It uses preference headers.

这是我的问题:

  1. 如果您使用的是带有单个PreferenceFragment且具有与API 19以前版本兼容的简单,单个preferences.xml文件,那么SettingsActivity应该扩展哪个类?Activity,PreferenceActivity或AppCompatPreferenceActivity(用于其所有支持方法和委派)?
  2. 您是否需要在SettingsActivity.onCreate()中调用 getFragmentManager().beginTransaction().replace(android.R.id.content,new SettingsFragment()).commit()?
  3. 通过各种组合,我将得到空白的白色设置屏幕,没有操作栏或崩溃.在显示应用程序操作栏的活动中设置单个PreferencesFragment的正确方法是什么?

推荐答案

SettingActivity应该扩展什么类?

what class should SettingsActivity extend?

对我有用的是扩展 AppCompatActivity .

static final String ANIMATION = "animation" ;
static final String COUNTDOWN_ON_OFF = "countdown_on_off";

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

    if (getFragmentManager().findFragmentById(android.R.id.content) == null)
    {
        getFragmentManager().beginTransaction().add(android.R.id.content, new Prefs()).commit();
    }
}

我踢出了所有与首选项头相关的代码,并为我的 PreferenceFragment

I kicked out all the generated code related to preference headers and kept some template methods/ variables (which Android Studio generated in some earlier version) for my PreferenceFragment

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

        // Bind the summaries of EditText/List/Dialog/Ringtone preferences
        // to their values. When their values change, their summaries are
        // updated to reflect the new value, per the Android Design
        // guidelines.

        // findPreference() uses android:key like in preferences.xml !

        bindPreferenceSummaryToValue(findPreference(ANIMATION));

    }
}

我的 Activity 类中的静态方法(改编自模板).您可能要检查其他首选项类型:

A static method in my Activity class (adapted from the template). You may want to check for other preference types:

 /**
 * Binds a preference's summary to its value. More specifically, when the
 * preference's value is changed, its summary (line of text below the
 * preference title) is updated to reflect the value. The summary is also
 * immediately updated upon calling this method. The exact display format is
 * dependent on the type of preference.
 *
 * @see #sBindPreferenceSummaryToValueListener
 */
private static void bindPreferenceSummaryToValue(Preference preference)
{
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.

    if (preference instanceof CheckBoxPreference)
    {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                                                                 PreferenceManager
                                                                         .getDefaultSharedPreferences(preference.getContext())
                                                                        .getBoolean(preference.getKey(), true));
    }
    else
    {
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                                                                 PreferenceManager
                                                                         .getDefaultSharedPreferences(preference.getContext())
                                                                         .getString(preference.getKey(), ""));
    }
}

最后,将 Preference.OnPreferenceChangeListener 作为 Activity (也从模板改编)中的静态变量:

And finally, the Preference.OnPreferenceChangeListener as static variable in the Activity (also adapted from the template):

   /**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.<br>
 * template by Android Studio minus Ringtone Preference
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener()
{
    @Override
    public boolean onPreferenceChange(Preference preference, Object value)
    {
        String stringValue = value.toString();

        if (preference instanceof ListPreference)
        {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                    index >= 0
                            ? listPreference.getEntries()[index]
                            : null);

        }
        else if (preference instanceof RingtonePreference)
        {
            // my app didn't need that
            return true;
        }
        else if (preference instanceof CheckBoxPreference)
        {
            Context ctx = preference.getContext();
            boolean isChecked = (Boolean) value;

            if (preference.getKey().equals(ANIMATION))
            {
                preference.setSummary(isChecked ? ctx.getString(R.string.sOn) : ctx.getString(R.string.sOff));
            }
            else if (preference.getKey().equals(COUNTDOWN_ON_OFF))
            {
                preference.setSummary(isChecked ? ctx.getString(R.string.sWhenPaused) : ctx.getString(R.string.sNever) );
            }
        }
        else
        {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        return true;
    }
};
}

这篇关于设置Android PreferenceFragment的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆