Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...