ZOFTINO.COM

Android View Shadow Effect

Android UI elements can be configured to draw shadows using elevation property. Elevation of a view can be set in code by calling setElevation method and in xml using elevation attribute. Below picture shows text views with elevation and without elevation.

Elevation

 





 
android elevation shadow

Android View Elevation Shadow Shape

Outline object represents the shape of view shadows. Outline provider creates outline object that defines shadow shape. The default view outline provider treats background shape of a view as shadow shape. You can change this behavior by creating custom outline provider for views. Below picture shows change in shape of shadow with the change in background. When you set background of a view to round cornered image, elevation draws round cornered shadow.

custom_rect.xml


    
    

Elevation shadow background shape

 





 
android elevation outline

Android View Elevation Custom Shadow Shape

As learned above, default view outline provider draws shadows based on the background shape. If you want to draw shadows in a different way, you need to provide custom view outline provider. You can create custom view outline provider by extending ViewOutlineProvider class and overriding getOutline() method. Then set the custom outline provider to the view by using setOutlineProvider() method.

Custom ViewOutlineProvider Example

Below example shows how to create custom view outline provider. It provides round cornered rectangle outline for the view it is set to.

android custom outline provider

Activity

 package com.zoftino.materialdesign;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

public class ShadowActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shadow_activity);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.z_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        TextView textView = (TextView) findViewById(R.id.shadow_txt);
        textView.setOutlineProvider(new ZoftinoCustomOutlineProvider(8));
        textView.setClipToOutline(true);
    }
}
 

Custom view outline provider

 package com.zoftino.materialdesign;


import android.graphics.Outline;
import android.view.View;
import android.view.ViewOutlineProvider;

public class ZoftinoCustomOutlineProvider extends ViewOutlineProvider {

    int roundCorner;

    public ZoftinoCustomOutlineProvider(int round) {
        roundCorner = round;
    }

    @Override
    public void getOutline(View view, Outline outline) {
        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), roundCorner);
    }
}
 

Layout