Nicolas
Nicolas

Reputation: 77

SwitchPreference Vibration

I have a SwitchPreference which is supposed to handle if the phone vibrates or not.

I currently have this:

 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);

I want to be able to do this:

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

What is the correct syntax I should be using?

Upvotes: 1

Views: 336

Answers (1)

Amir
Amir

Reputation: 16587

In your preference xml:

<SwitchPreference
    android:key="Changetheme"
    android:title="vibrate"
    android:defaultValue="false" />

And your java code should be something like:

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

Upvotes: 1

Related Questions