• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How Can I Disable A SharedPreference Programatically?

RichSz

Not Entitled
I'm a C++ programmer working my way through my first app and I've run into a wall. I'm sure there is a very simple solution to this but my lack of experience is hobbling me.

I have a preferences Activity which contains a CheckboxPreference controlling whether the app uses the vibrator or not. If the device running the app does not have a vibrator, I'd like this to be disabled (greyed out). I've defined the checkbox in XML and given it an ID.

Code:
    <CheckBoxPreference
        android:key="vibrateEnable"
        android:summaryOn="@string/prefVibeEnabledSummary"
        android:summaryOff="@string/prefVibeDisabledSummary"
        android:disableDependentsState="false"
        android:title="@string/titleVibEnablePref"
        android:id="@+id/vibPrefEnable"/>
When the preference Activity's onCreate is executed, I plan on making a check if the device has a vibrator and enabling/disabling the Checkbox accordingly.

The problem is I can't seem to get a reference to the actual Checkbox. I can read its state easily enough but can't figure out how to get the reference to the object via R.whatever. I want to learn this the right way by using XML wherever possible and not just new up a Checkbox and add it to the preferences Activity as a SharedPreference.

Can anyone help a noob out?

On a side note, why does the SDK reference believe there is a hasVibrator() method (Vibrator | Android Developers), yet Eclipse staunchly disagrees?
 
Should be something like:

Code:
CheckBoxPreference myCheckBox = (CheckBoxPreference) findViewByID(R.id.vibPrefEnable);
myCheckBox.setEnabled(false);

make sure you call it after setContentView()
 
Thanks for the response!

Unfortunately that didn't work. I got an "Cannot cast from View to CheckBoxPreference" error. In this Activity, I hadn't done a setContentView() because I thought addPreferencesFromResource(R.xml.prefs) took care of it. Even adding the setContextView() didn't resolve the issue.

I've been going through O'Reilly's "Learning Android" and modifying the Yamba example to do what I need. It seems pretty close to the pieces I'm looking for but clearly due to my lack of experience, I'm still a bit baffled. C++ is so much easier! ;)
 
Ah weird, it doesnt subclass View.... sometimes the API makes me want to smack the Google engineers with a wet fish. Sorry about that.

Anyways, this is actually probably why I dont create preference screens with XML. It's the only activity I just layout in Java. Not really an answer for you but... maybe it helps.

You'd at least have the ref to it and could call methods on it etc...I dont really know of any other way to target it by id...
 
Back
Top Bottom