java - SwitchPreference and CheckBoxPreference in code -


i creating preference page app

after api-14, switchpreference available. , use replace checkboxpreference on api14+ devices

it easy use res/xml , res/xml-14 correct xml resource

however, in coding part, not convenient switching preference according api.

public class settingactivity extends preferenceactivity {     private checkboxpreference enable;     private switchpreference enablev14;      @override     protected void oncreate(bundle savedinstancestate) {         addpreferencesfromresource(r.xml.setting);         if (build.version.sdk_int < 14)             enable = (checkboxpreference) findpreference(key_enable);         else             enablev14 = (switchpreference) findpreference(key_enable);     }     ... } 

now way use if-clause check build.version , corresponding object process it. quite inconvenient , hard manage code. has smarter way it?

maybe set android:key attribute both of switchpreference , checkboxpreference xml, this:

<?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android">     <checkboxpreference         android:key="pref_sync"         android:title="@string/pref_sync"         android:defaultvalue="true" /> </preferencescreen> 

and

<?xml version="1.0" encoding="utf-8"?> <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android">     <switchpreference         android:key="pref_sync"         android:title="@string/pref_sync"         android:defaultvalue="true" /> </preferencescreen> 

and can check if key returns true or false on code, this:

public class settingactivity extends preferenceactivity {  @override protected void oncreate(bundle savedinstancestate) {     addpreferencesfromresource(r.xml.setting);     preferencemanager preferencemanager = getpreferencemanager();     if (preferencemanager.getsharedpreferences().getboolean("pref_sync", true)){         // switch on     } else {         // switch off     }     ... } 

hope works you.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -