Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set shadow to a View in android?

I want to know how to add a shadow layer to any general View in android. for eg: suppose i have a layout xml, showing something like this..

<?xml version="1.0" encoding="utf-8"?>   <LinearLayout       android:layout_height="wrap_content"       android:layout_width="wrap_content"       <Button....       ...   </LinearLayout>   

Now when it is displayed I want to have a shadow around it.

like image 879
aqs Avatar asked Dec 10 '10 07:12

aqs


People also ask

How to add elevation to view in android?

To set the default (resting) elevation of a view, use the android:elevation attribute in the XML layout. To set the elevation of a view in the code of an activity, use the View. setElevation() method. To set the translation of a view, use the View.

How do I add shadows to Kotlin?

Kotlin Android – TextView Shadow Effect To get shadow for TextView in Android, set android:elevation attribute, with required amount of elevation from the base level, for the TextView widget in layout XML file. For elevation to be effective, we should set background for the TextView.

What is elevation android?

Elevation (Android) Elevation is the relative depth, or distance, between two surfaces along the z-axis. Specifications: Elevation is measured in the same units as the x and y axes, typically in density-independent pixels (dp).


1 Answers

The best way to create a shadow is to use a 9patch image as the background of the view (or a ViewGroup that wraps the view).

The first step is to create a png image with a shadow around it. I used photoshop to create such an image. Its really simple.

  • Create a new image with Photoshop.
  • Add a layer and create a black square of 4x4.
  • Create a shadow on the layer by selecting the layer in layer explorer and clicking on a button titled fx and choosing drop shadow.
  • Export the image as png.

The next step is to create 9-patch drawables from this image.

  • Open draw9patch from android-sdk/tools
  • Open the image in draw9patch
  • Create 4 black lines on the four sides of the square like the following and then save the image as shadow.9.png.

Now you can add this shadow as the background of the views you want to add the shadow to. Add shadow.9.png to res/drawables. Now add it as a background:

<LinearLayout   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:background="@drawable/shadow"   android:paddingBottom="5px"   android:paddingLeft="6px"   android:paddingRight="5px"   android:paddingTop="5px" > 

I recently wrote a blog post that explains this in detail and includes the 9patch image that I use for creating the shadow.

like image 195
Sapan Diwakar Avatar answered Oct 05 '22 19:10

Sapan Diwakar