【问题标题】:Android preferences without an xml - Using fragments没有 xml 的 Android 首选项 - 使用片段
【发布时间】:2013-07-05 21:42:31
【问题描述】:

您好,我想在我的应用程序中创建首选项,但由于一些依赖问题,我根本无法使用资源。 我可以使用以下代码做到这一点:

public class DTMainActivity extends PreferenceActivity {

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

    setPreferenceScreen(defaultPref());
    setDependencies();


}

// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
    PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);

    SwitchPreference dLogTracingEnablePref = new SwitchPreference(this);
    dLogTracingEnablePref.setTitle(R_Class.R_String.dLogTracingEnablePrefString);
    dLogTracingEnablePref.setDisableDependentsState(false);
    dLogTracingEnablePref.setChecked(true);
    dLogTracingEnablePref.setKey(R_Class.R_String.dLogTracingEnablePrefKey);
    root.addPreference(dLogTracingEnablePref);
}

我想使用基于片段的新方法来做到这一点,而不使用 getPreferenceManager 等已弃用的 API。我可以在没有任何资源的情况下创建所有其他 UI 布局元素,如 linearlayout 等。但是当涉及到偏好时和 PreferenceFragment 类,所有可用的都是 addPreferencesFromResource() ,它需要一个 XML。有谁能帮帮我吗?

【问题讨论】:

    标签: android android-preferences


    【解决方案1】:

    我设法使用 PreferenceFragment 实现了它,没有 addPreferencesFromResource(), 相反,我只是像你刚才那样创建了 PreferenceScreen 并使用了

    尝试使用 bindPreferenceSummaryToValue,考虑“p”是一个 PreferenceScreen,其中已经添加了 Preferences,(并且之前已经创建和配置了)

    PreferenceScreen p = createPreferences();//a method that creates a PreferenceScreen and add some preferences into it
    this.setPreferenceScreen(p);
    bindPreferenceSummaryToValue(p.findPreference("preference_key"));
    

    我回复了一个有类似问题的人here ..也许你可以看看

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 2017-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2014-03-10
      相关资源
      最近更新 更多