gpt4 book ai didi

android - SwitchPreference振动

转载 作者:行者123 更新时间:2023-11-30 01:02:37 24 4
gpt4 key购买 nike

我有一个 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

我应该使用的正确语法是什么?

最佳答案

在你的 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");
}
}
}

关于android - SwitchPreference振动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39234826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com