Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android “elevation” is not showing a shadow under a CustomView

I Have a CustomView working on pre-Lollipop, now I tried to apply android:elevation and android:translateZ on Lollipop devices but doesn't seems to work.

<com.example.CustomView
    android:id="@+id/myview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:elevation="10dp">
</com.example.CustomView>

What i missing?

like image 993
rnrneverdies Avatar asked Dec 16 '14 05:12

rnrneverdies


People also ask

What is shadow elevation?

Elevation helps users understand the relative importance of each element and focus their attention to the task at hand. The elevation of a view, represented by the Z property, determines the visual appearance of its shadow: views with higher Z values cast larger, softer shadows.

Can we change elevation color in Android?

is it possible to change the shadow color produced by the xml elevation property? I want the shadow be dynamically changed by code. No, the color of the shadow provided by the framework cannot be changed.


1 Answers

As mentioned in Defining Shadows and Clipping Views

You should implement ViewOutlineProvider abstract class by which a View builds its Outline, used for shadow casting and clipping

Rectangular CustomView

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);
        }
    }

    //...
}

note: This feature is only supported by API21, pre API21 should use 9-patch.

like image 141
rnrneverdies Avatar answered Sep 30 '22 03:09

rnrneverdies