我有一个SwitchPreference,如果手机振动,它应该处理。
我目前有这个:
import android.os.Vibrator;
...
public static final String PREF_CHANGE_THEME = "Changetheme";
private SwitchPreference mSwitchPreference;
private static SharedPreferences sPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSwitchPreference = (SwitchPreference) findPreference(PREF_CHANGE_THEME);
我希望能够做到这一点:
sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
mSwitchPreference = (SwitchPreference)
//If enabled execute the following:
Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
//Else: nothing
我应该使用的正确语法是什么?
答案 0 :(得分:1)
在preference
xml:
<SwitchPreference
android:key="Changetheme"
android:title="vibrate"
android:defaultValue="false" />
你的java代码应该是这样的:
public class SettingActivity extends PreferenceActivity implements onSharedPreferenceChangeListener {
public SwitchPreference mSwitchPreference;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.sample);
mSwitchPreference = (SwitchPreference) findPreference(PREF_CHANGE_THEME); //Preference Key
mSwitchPreference.setOnPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(PREF_CHANGE_THEME)) {
boolean isEnable = sharedPreferences.getBoolean(PREF_CHANGE_THEME, false);
//Do whatever you want here. This is an example.
if (isEnable) {
mSwitchPreference.setSummary("Enabled");
} else {
mSwitchPreference.setSummary("Disabled");
}
}
@Override
public void onResume() {
super.onResume();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(TestPrefActivity.this);
boolean isEnable = preferences.getBoolean(PREF_CHANGE_THEME, false);
if (isEnable) {
mSwitchPreference.setSummary("Enabled");
} else {
mSwitchPreference.setSummary("Disabled");
}
}
}