有一部分Material design特性只能在5.0或者更高的版本上才能使用,包括以下这些:
- Activity transitions(activity切换动画效果)
- Touch feedback(触摸反馈)
- Reveal animations
- Path-based animations
- Vector drawables
- Drawable tinting
// 如果是5.0或者更高
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// 使用material design特性的代码
} else {
// 实现没有material design特性的代码
}
下面介绍Material design的主题(theme)兼容性,想要在5.0上使用属于material design的主题又要保证能够兼容5.0之前主题,方法就是分别在res/values/styles.xml
和res/values-v21/styles.xml
中定义一个同名的主题,比如AppBaseTheme,然后在res/values/styles.xml中AppBaseTheme样式下定义5.0之前的样式的属性,在
res/values-v21/styles.xml
中AppBaseTheme样式下定义5.0的样式的属性,这样就能适配啦!
res/values/styles.xml
下的代码:
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- toolbar(actionbar)颜色 -->
<item name="colorPrimary">#4876FF</item>
<!-- 状态栏颜色 -->
<item name="colorPrimaryDark">#3A5FCD</item>
<!-- 窗口的背景颜色 -->
<item name="android:windowBackground">@android:color/white</item>
</style>
res/values-v21/styles.xml
下的代码:
<style name="AppBaseTheme">
<!-- 底部导航栏颜色,5.0才有的 -->
<item name="android:navigationBarColor">#4876FF</item>
</style>
都定义好之后再AndroidManifest.xml中使用就行了
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppBaseTheme">
</application>
Material design的布局(layout)兼容性和主题(theme)类似,分别在res/layout/
和res/layout-v21/
中定义同名布局文件即可,如果不想写重复的布局代码,用<include/>引用相同的布局文件就行了。
还好,还好,有v7兼容包(r21),注意是版本是21。v7兼容个包可以使用下面的特性:
- Material design styles for some system widgets when you apply one of the
Theme.AppCompat
themes. - Color palette theme attributes in the
Theme.AppCompat
themes. - The
RecyclerView
widget todisplay data collections. - The
CardView
widget tocreate cards. - The
Palette
class toextract prominent colors from images.
Theme.AppCompat
可以为以下控件提供主题样式:
Palette可以从图片中提取颜色,也能直接使用
Theme.AppCompat
中的颜色:
<!-- extend one of the Theme.AppCompat themes -->
<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
<!-- customize the color palette -->
<item name="colorPrimary">@color/material_blue_500</item>
<item name="colorPrimaryDark">@color/material_blue_700</item>
<item name="colorAccent">@color/material_green_A200</item>
</style>
Material Design的特性不是所有都兼容,还是去开源的东西吧!
1.EasyAndroidAnimations:https://github.com/2359media/EasyAndroidAnimations
2.Android-Material-Example:https://github.com/saulmm/Android-Material-Example
3.materialish-progress:https://github.com/pnikosis/materialish-progress
4.material-design-icons:https://github.com/google/material-design-icons
还有一个:https://github.com/lightSky/MaterialDesignCenter