我想从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);