Elevation on Android Lollipop not working

后端 未结 9 1524
长情又很酷
长情又很酷 2020-11-28 12:22

I am trying to make use of the elevation property in the latest Android Lollipop preview release. I set the targetSdk to 21 and the theme to Material. Next i added a backgro

9条回答
  •  离开以前
    2020-11-28 13:11

    As noted earlier, this is an open bug in Android : if the background drawable uses a solid color with transparency, then the shadow won't be shown.

    To work around the issue, display the background in its own separate view and set the alpha on that view. Wrap the background view and the TextView in a RelativeLayout to place the background directly under the TextView and use android:layout_alignLeft, android:layout_alignBottom etc to make it the same size. They need to be at the same elevation, and the background must appear before the TextView in the xml so it is drawn under it.

    
    
        
    
    
        
    
    
    

    The drawable is the same as yours but without transparency:

    
        
        
    
    

    Result:

    A few notable points:

    • You must ensure that the enclosing RelativeLayout is large enough to display the shadow. If you just set its dimensions to wrap_content without padding, the shadow will be clipped to the layout's bounds. As explained in this question, you can use padding and set android:cipToPadding="false" to make it large enough for the shadow. You might not need as much padding in this case, I haven't experimented with that.
    • In this case we need to use a separate view for the background because if we had set the alpha directly on the TextView then the text would have been affected as well. Depending on your use case you might not need a separate view and enclosing layout and could just just have one view, with alpha set on the view and no transparency in the drawable.

提交回复
热议问题