简体   繁体   中英

How to use new API elements like Switch so, that the app is compatible with older Android version?

I want to use new UI elements like Switch for new Android devices, and by older devices I would use something else like Button.

I have created to layouts

~/res/
   layout/main.xml
   layout-v14/main.xml

that has different elements like Button in layout/main.xml and Switch in layout-v14/main.xml

But how can I add different elements in the Activity, without to get Exception like

Could not find class 'android.widget.Switch' ... 

You can reference Build.VERSION.SDK_INT to inspect the device's API level at runtime. That way, you can add conditional code in your Java classes that will vary its behavior based on the user's API level, like so:

if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ) {
  // Some code that requires API level 14+
} else {
  // Code that will run on lower API levels instead
}

对于Switch您可以尝试使用SwitchCompat库,以使其向后兼容。

You usually include the Support Library in your project dependencies for that purpose. (http://developer.android.com/tools/extras/support-library.html)

You can then use new objects (like Fragments for example) with older devices.

Unfortunately, Switch is not among them...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM