我有一个自定义视图在Lollipop之前工作,现在我尝试在Lollipop设备上应用android:elevation
和android:translateZ
,但似乎不起作用。
<com.example.CustomView
android:id="@+id/myview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="10dp">
</com.example.CustomView>
我错过了什么?
答案 0 :(得分:24)
正如Defining Shadows and Clipping Views
中所述你应该实现ViewOutlineProvider
抽象类,View
构建它的Outline
,用于阴影投射和剪辑
public class CustomView extends View {
// ..
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
/// ..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setOutlineProvider(new CustomOutline(w, h));
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private class CustomOutline extends ViewOutlineProvider {
int width;
int height;
CustomOutline(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void getOutline(View view, Outline outline) {
outline.setRect(0, 0, width, height);
}
}
//...
}
注意:此功能仅受API21支持,API21之前应使用9-patch。