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.