Android“提升”未在CustomView下显示阴影

前端之家收集整理的这篇文章主要介绍了Android“提升”未在CustomView下显示阴影前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个CustomView工作在前Lollipop,现在我尝试在Lollipop设备上应用 android:elevation和android:translateZ但似乎不起作用.
  1. <com.example.CustomView
  2. android:id="@+id/myview"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:elevation="10dp">
  6. </com.example.CustomView>

我错过了什么?

解决方法

Defining Shadows and Clipping Views所述

您应该实现ViewOutlineProvider抽象类,View构建其Outline,用于阴影投射和剪切

矩形CustomView

  1. public class CustomView extends View {
  2.  
  3. // ..
  4.  
  5. @Override
  6. protected void onSizeChanged(int w,int h,int oldw,int oldh) {
  7. /// ..
  8. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  9. setOutlineProvider(new CustomOutline(w,h));
  10. }
  11. }
  12.  
  13. @TargetApi(Build.VERSION_CODES.LOLLIPOP)
  14. private class CustomOutline extends ViewOutlineProvider {
  15.  
  16. int width;
  17. int height;
  18.  
  19. CustomOutline(int width,int height) {
  20. this.width = width;
  21. this.height = height;
  22. }
  23.  
  24. @Override
  25. public void getOutline(View view,Outline outline) {
  26. outline.setRect(0,width,height);
  27. }
  28. }
  29.  
  30. //...
  31. }

注意:此功能仅由API21支持,前API21应使用9-patch.

猜你在找的Android相关文章