我的偏好是这样的:
的settings.xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="@string/sectionOneTitle" >
<EditTextPreference
android:title="@string/setModuleName"
android:summary="@string/setModuleNameSum"
android:key="moduleID"/>
</PreferenceCategory>
<PreferenceCategory android:title="@string/sectionTwoTitle" >
<EditTextPreference
android:title="@string/setPhoneNumber"
android:summary="@string/setPhoneNumberSum"
android:key="phoneNumber"/>
</PreferenceCategory>
<PreferenceCategory android:title="@string/sectionThreeTitle" >
<CheckBoxPreference android:title="@string/setSmsSend"
android:key="setSmsSend" android:summary="@string/setSmsSendSum" />
</PreferenceCategory>
</PreferenceScreen>
设置活动
public class SettingsActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
现在我需要在设置或取消设置复选框时调用我的MAINActivity中的方法。这可能吗?
由于
答案 0 :(得分:6)
为您的活动添加OnSharedPreferenceChangeListener
:
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
...
public class MAINActivity extends Activity {
private OnSharedPreferenceChangeListener listener =
new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("setSmsSend") {
smsSendPrefChanged(); // the function you want called
}
}
};
@Override
protected void onCreate() {
super.onCreate();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(listener);
...
}
@Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.unregisterOnSharedPreferenceChangeListener(listener);
...
}
...
}
答案 1 :(得分:-1)
使用 PreferenceFragmentCompat
public class FragmentSettings
extends PreferenceFragmentCompat
implements SharedPreferences.OnSharedPreferenceChangeListener
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.app_preferences);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
switch(key)
{
case "KEY1":
// DO STUFF
break;
case "KEY2":
// DO STUFF
break;
}
}