Question

i wanna use SwitchPreference sToggle when api>=14 and use CheckBoxPreference chToggle when api<14

i get exception with my code

public class SettingsActivity extends PreferenceActivity {
SwitchPreference sToggle;
CheckBoxPreference chToggle;

...

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

...

if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
        sToggle = new CheckBoxPreference(this);
        sToggle.setTitle("One");
        targetCategory.addPreference(sToggle);
    } else {
        chToggle = new CheckBoxPreference(this);
        chToggle.setTitle("Two");
        targetCategory.addPreference(chToggle);
    }

can u help me?)

Was it helpful?

Solution

SwitchPreference sToggle; is defined by your code even on API level < 14. That would be the exception I'd assume.

The class does not exist at all on those API levels, so you must not use it at all. Kind of not even mention it in the code. Or technically: don't do anything that loads that class.

You are however allowed to declare sToggle to be a variable of a supertype that existed, e.g.

public class SettingsActivity extends PreferenceActivity {
    Preference sToggle;

Then move the code that uses the SwitchPreference into another class that is not loaded on lower API levels. E.g.

 class ToggleNew {
      public static Preference getToggle() {
          return new SwitchPreference();
      }
 }
 class ToggleOld {
      public static Preference getToggle() {
          return new CheckboxPreference();
      }
 }

Your original class can now use / load the version that you want dynamically.

Preference p;
if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
        p = ToggleNew.getToggle();
} else {
        p = ToggleOld.getToggle();
}

You need to adjust that a bit but that's the general approach how to use classes on some API levels but not on others.

OTHER TIPS

Use SwitchPreferenceCompat instead of SwitchPreference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top