使用 Androidx 库
implementation 'androidx.preference:preference:1.1.1'
然后创建xml
文件夹并在下面添加您的SwitchPreferenceCompat
喜欢:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<SwitchPreferenceCompat
android:id="@+id/vibrate"
android:key="vibrate"
android:summary="It will vibrate your phone"
android:title="Vibrate"/>
<SwitchPreferenceCompat
android:id="@+id/changeTheme"
android:key="theme"
android:title="Change Theme"
android:summary="It will toggle your app theme"/>
</androidx.preference.PreferenceScreen>
然后创建SwitchPreferenceCompatActivity
如下:
public class SwitchPreferenceCompatActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_preference_compat);
if(savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.preferences_container, new MySettingsFragment())
.commit();
}
}
public static class MySettingsFragment extends PreferenceFragmentCompat {
SharedPreferences.OnSharedPreferenceChangeListener listener;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.my_switch_preference_compat, rootKey);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.e("key", key);
if(key.equals("vibrate") && sharedPreferences.getBoolean("vibrate", false)) {
vibratePhone();
}
}
};
}
@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(listener);
}
@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(listener);
}
private void vibratePhone() {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null) {
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
vibrator.vibrate(500);
}
}
}
}
}
注意:添加<uses-permission android:name="android.permission.VIBRATE" />
清单文件的权限。