Android View 的阴影效果
Android 5.0之前View通常只有X、Y属性,而在5.0之后有了Z属性,即2个View之间在Z轴上的距离。
Z属性由XML中elevation和代码中translationZ构成
Z = elevation + translationZ
1. 阴影效果实现
XML中使用elevation属性
<TextView
android:id="@+id/tv"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="@color/colorAccent"
android:elevation="10dp" />
代码中设置TranslationZ属性
View tv = findViewById(R.id.tv);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tv.setTranslationZ(10);
}
2.一些设置了却无法显示阴影的原因:
- 控件必须设置背景色,且不能为透明
- 控件与父控件的边界之间需有足够空间绘制出阴影才行
网友评论