我正在开发一款可让用户打开/关闭某些特定功能的应用,例如Wi-Fi,蓝牙等。但我似乎无法做到这一点,首选项屏幕上的切换按钮没有响应我的设置java代码。这是我尝试过的事情
SettingsFragment.java
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences
.OnSharedPreferenceChangeListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loads the XML preferences file.
addPreferencesFromResource(R.xml.preferences);
}
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if(key.equals(getString(R.string.wifi))){
WifiManager wifiManager = (WifiManager)getActivity().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
}
}
preference.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Battery Saver Mode">
<SwitchPreference
android:defaultValue="true"
android:key="battery_tone"
android:title="@string/pref_title_new_message_notifications"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_bluetooth"
android:key="@string/bluetooth"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_mobile_data"
android:key="mobile_data"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_vibrate"
android:key="vibrate"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_sync"
android:key="sync"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_wifi"
android:key="@string/wifi"/>
<SwitchPreference
android:defaultValue="true"
android:title="@string/pref_airplane_mode"
android:key="airmode"/>
</PreferenceCategory>
</PreferenceScreen>