问题
I cannot use Lollipop elevation
property because I need to target devices from API 18.
I need to place a shadow on the right and left side of a view.
This is what I tried so far :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<item>
<shape >
<!-- set the shadow color here -->
<stroke
android:width="2dp"
android:color="#7000" />
<!-- setting the thickness of shadow (positive value will give shadow on that side) -->
<padding
android:bottom="0dp"
android:left="2dp"
android:right="2dp"
android:top="0dp" />
<corners android:radius="3dp" />
</shape>
</item>
<!-- Background -->
<item>
<shape>
<solid android:color="@color/salmon" />
<corners android:radius="3dp" />
</shape>
</item>
</layer-list>
I tried adding gradients
in the first item, but it spreads from left to right which is not what I am looking fo. Is there a way to isolate two unique gradients for each side ?
This is what I am trying to do :
回答1:
You can try using a gradient
contained within a rectangle, which you can size: example below is a shadow I used for Navigation Drawer. You can modify this to fit your needs.
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#111"
android:endColor="#00000000">
</gradient>
<size
android:height="@dimen/activity_vertical_margin"
android:width="5dp">
</size>
</shape>
Alternitively, you can use a CardView from v7 CardView support library, which supports Android api 7+.
回答2:
You need to create your own drawable for it.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="@android:color/white"
android:startColor="@color/black_38">
</gradient>
<size
android:height="4dp">
</size>
</shape>
And then for example with help of relative layout to align to any side of your layout. For me it's bottom shadow of custom app bar.
...
<View
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:background="@drawable/app_bar_shadow"
android:layout_height="4dp"/> // height of your shadow
来源:https://stackoverflow.com/questions/34401334/android-how-to-create-gradient-shadow-on-left-and-right-of-view