我想从CheckBoxPreference获取值,我已经在Convert/res/xml/settings.xml中定义了它,这是它的外观:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <CheckBoxPreference
        android:key="allow_internet"
        android:title="@string/internet_label"
        android:summaryOn="@string/internet_on"
        android:summaryOff="@string/internet_off"
        android:defaultValue="true" />
    <CheckBoxPreference
        android:key="decimal_output"
        android:title="@string/decimal_title"
        android:summaryOn="@string/decimal_summary_on"
        android:summaryOff="@string/decimal_summary_off" />
</PreferenceScreen>


我的问题是如何获取CheckBoxPreference文件中MainActivity.java的值,因为android:id没有CheckBoxPreference属性,Settings.java中也有Convert/scr/.../Settings.java文件,它看起来喜欢:

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Settings extends PreferenceActivity {

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}

最佳答案

CheckboxPreferences存储在SharedPreferences中。在您的MainActivity中,您可以使用:

PreferenceManager.setDefaultValues(this, R.xml.settings, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean allowInternet = sharedPreferences.getBoolean("allow_internet", true);

09-19 20:29