如何在Android中的linearlayout周围显示阴影?


79

如何显示线性布局的阴影。我想要带有圆线布局周围阴影的白色圆形背景。到目前为止,我已经做到了。

<LinearLayout
 android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:background="@xml/rounded_rect_shape"
android:orientation="vertical"
android:padding="10dp">
<-- My buttons, textviews, Imageviews go here -->
</LinearLayout>

以及xml目录下的rounded_rect_shape.xml

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
   android:shape="rectangle" >

   <solid android:color="#ffffff" />

   <corners
      android:bottomLeftRadius="3dp"
      android:bottomRightRadius="3dp"
      android:topLeftRadius="3dp"
      android:topRightRadius="3dp" />
</shape>

Answers:


28

Android中没有这样的属性来显示阴影。但是可能的方法是:

  1. 添加带有灰色的普通LinearLayout,在其上添加您的实际布局,底部和右侧的边距等于1或2 dp

  2. 制作带有阴影的9色块图像并将其设置为线性布局的背景


9补丁是最好的方法!
Andranik

有没有办法将9色块与自定义多边形一起使用?我尝试使用此工具inloop.github.io/shadow4android,但它只是为椭圆/矩形形状创建阴影
边缘

143

通过实现将用作LinearLayoout的背景的层列表,还可以解决该问题。

将background_with_shadow.xml文件添加到中res/drawable。包含:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <shape 
            android:shape="rectangle">
        <solid android:color="@android:color/darker_gray" />
        <corners android:radius="5dp"/>
        </shape>
    </item>
    <item android:right="1dp" android:left="1dp" android:bottom="2dp">
        <shape 
            android:shape="rectangle">
        <solid android:color="@android:color/white"/>
        <corners android:radius="5dp"/>
        </shape>
    </item>
</layer-list>

然后在您的LinearLayout中将图层列表添加为背景。

<LinearLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="@drawable/background_with_shadow"/>

喔!我做了一些,看起来不太好。如果您正在寻找整体式标准,它看起来很完美。多谢,伙计。
jfcogato

效果不错,谢谢!但是我有一个较小的-难以觉察的问题:阴影并不是真的靠近白色布局,而是共享居中的空间。如果我说的不够清楚,请尝试使用100dp代替1dp进行相同的代码。我知道,在大多数情况下它是看不见的,但是如果有人可以为我提供解决方案,那将是完美的!
Poutrathor

1
@Poutrathor,有趣的是您注意到了这个问题。不幸的是,我目前没有其他解决方案。您想要完成什么?也许有人可以进一步帮助您解决问题。
muthee

“您想完成什么?” 完美,当然!开玩笑,我注意到了,所以我举报。您的解决方案非常适合时尚的短阴影,现在我很高兴使用它。希望我能给您更多的支持:)
Poutrathor

3
要添加的是,上部形状是阴影(!),而下部形状是主要的较大部分。
sandalone

30

好吧,这很容易实现。

只需构建一个GradientDrawable来自黑色并变为透明颜色的,然后使用父关系将形状放置在要具有阴​​影的View附近,然后只需将height或width的值赋予即可。

这是一个示例,必须在内部创建此文件res/drawable,我将其命名为shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <gradient
        android:startColor="#9444"
        android:endColor="#0000"
        android:type="linear"
        android:angle="90"> <!-- Change this value to have the correct shadow angle, must be multiple from 45 -->
    </gradient>

</shape>

将以下代码放在上方LinearLayout,例如,将android:layout_width和设置android:layout_heightfill_parent2.3dp,则您的上会有很好的阴影效果LinearLayout

<View
    android:id="@+id/shadow"
    android:layout_width="fill_parent"
    android:layout_height="2.3dp"  
    android:layout_above="@+id/id_from_your_LinearLayout" 
    android:background="@drawable/shadow">
</View>

注意1:如果增加,android:layout_height将显示。

注意2:android:layout_above="@+id/id_from_your_LinearLayout"如果要将代码放在RelativeLayout中,请使用属性,否则将其忽略。

希望它能帮助某人。


您好...我知道这很旧...但是您是说要在矩形视图结构周围获得阴影效果的唯一方法是创建另一个矩形结构,然后将它们相应地对齐???...谢谢...我是Android
新手

您好@dsdsdsdsds我不确定这是否是获得阴影效果的唯一方法,因为材质设计引入了很多设计资源,回家后我会看一下,如果有发现我会在这里评论。
Murillo Ferreira

18

对于棒棒糖及以上,您可以使用海拔高度

对于旧版本:

这是来自以下网站的懒惰黑客:http : //odedhb.blogspot.com/2013/05/android-layout-shadow-without-9-patch.html

(toast_frame在KitKat上不起作用,阴影已从多士炉中移除)

只需使用:

android:background="@android:drawable/toast_frame"

要么:

android:background="@android:drawable/dialog_frame"

作为背景

例子:

<TextView
        android:layout_width="fill_parent"
        android:text="I am a simple textview with a shadow"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="16dp"
        android:textColor="#fff"
        android:background="@android:drawable/toast_frame"
        />

并具有不同的背景颜色:

<LinearLayout
        android:layout_height="64dp"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:background="@android:drawable/toast_frame"
        android:padding="4dp"
        >
    <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Button shadow"
            android:background="#33b5e5"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="#fff"
            android:layout_gravity="center|bottom"
            />

</LinearLayout>

android:background="@android:drawable/alert_light_frame"适用于白色
abbasalim's

12

试试这个.. layout_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#CABBBBBB"/>
            <corners android:radius="2dp" />
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="0dp"
        android:top="0dp"
        android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

像这样应用于您的布局

 android:background="@drawable/layout_shadow"

7

我知道这很旧,但是大多数答案都需要大量额外的代码。

如果背景为浅色,则可以使用以下方法:

android:elevation="25dp"

这不是关于几行代码,而是您的代码应在所有设备上都能工作。您建议的海拔高度仅在API 21及更高版本中有效
-musooff

6

实际上,我同意@odedbreiner,但我将dialog_frame放在第一层内部,并将黑色背景隐藏在白色层下。

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@android:drawable/dialog_frame"
        android:right="2dp" android:left="2dp" android:bottom="2dp" android:top="5dp" >
        <shape android:shape="rectangle">
            <corners android:radius="5dp"/>
        </shape>
    </item>
    <item>
        <shape
            android:shape="rectangle">
            <solid android:color="@android:color/white"/>
            <corners android:radius="5dp"/>
        </shape>
    </item>
</layer-list>

2
  1. 保存此9.png。(将其命名为9.png

在此处输入图片说明

2.将其保存在您的计算机中drawable

3.将其设置为您的布局。

4.设置填充。

例如 :

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

.
.
.
</LinearLayout>

2

通过以下代码在DRAWABLE上通过名为“ shadow.xml”的示例创建新的XML,您可以使用以下代码(可以对其进行修改或找到另一个更好的方法):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/middle_grey"/>
        </shape>
    </item>

    <item android:left="2dp"
          android:right="2dp"
          android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="@color/white"/>
        </shape>
    </item>

</layer-list>

在LinearLayout或要创建阴影的另一个Widget中创建XML之后,您可以使用Background属性查看效果。就像这样:

<LinearLayout
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:paddingRight="@dimen/margin_med"
    android:background="@drawable/shadow"
    android:minHeight="?attr/actionBarSize"
    android:gravity="center_vertical">

1

您可以将以下类用于xml标签:

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.FloatRange;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import com.webappmate.weeassure.R;

/**
 * Created by GIGAMOLE on 13.04.2016.
 */
public class ShadowLayout extends FrameLayout {

    // Default shadow values
    private final static float DEFAULT_SHADOW_RADIUS = 30.0F;
    private final static float DEFAULT_SHADOW_DISTANCE = 15.0F;
    private final static float DEFAULT_SHADOW_ANGLE = 45.0F;
    private final static int DEFAULT_SHADOW_COLOR = Color.DKGRAY;

    // Shadow bounds values
    private final static int MAX_ALPHA = 255;
    private final static float MAX_ANGLE = 360.0F;
    private final static float MIN_RADIUS = 0.1F;
    private final static float MIN_ANGLE = 0.0F;
    // Shadow paint
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) {
        {
            setDither(true);
            setFilterBitmap(true);
        }
    };
    // Shadow bitmap and canvas
    private Bitmap mBitmap;
    private final Canvas mCanvas = new Canvas();
    // View bounds
    private final Rect mBounds = new Rect();
    // Check whether need to redraw shadow
    private boolean mInvalidateShadow = true;

    // Detect if shadow is visible
    private boolean mIsShadowed;

    // Shadow variables
    private int mShadowColor;
    private int mShadowAlpha;
    private float mShadowRadius;
    private float mShadowDistance;
    private float mShadowAngle;
    private float mShadowDx;
    private float mShadowDy;

    public ShadowLayout(final Context context) {
        this(context, null);
    }

    public ShadowLayout(final Context context, final AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShadowLayout(final Context context, final AttributeSet attrs, final int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setWillNotDraw(false);
        setLayerType(LAYER_TYPE_HARDWARE, mPaint);

        // Retrieve attributes from xml
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShadowLayout);

        try {
            setIsShadowed(typedArray.getBoolean(R.styleable.ShadowLayout_sl_shadowed, true));
            setShadowRadius(
                    typedArray.getDimension(
                            R.styleable.ShadowLayout_sl_shadow_radius, DEFAULT_SHADOW_RADIUS
                    )
            );
            setShadowDistance(
                    typedArray.getDimension(
                            R.styleable.ShadowLayout_sl_shadow_distance, DEFAULT_SHADOW_DISTANCE
                    )
            );
            setShadowAngle(
                    typedArray.getInteger(
                            R.styleable.ShadowLayout_sl_shadow_angle, (int) DEFAULT_SHADOW_ANGLE
                    )
            );
            setShadowColor(
                    typedArray.getColor(
                            R.styleable.ShadowLayout_sl_shadow_color, DEFAULT_SHADOW_COLOR
                    )
            );
        } finally {
            typedArray.recycle();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // Clear shadow bitmap
        if (mBitmap != null) {
            mBitmap.recycle();
            mBitmap = null;
        }
    }

    public boolean isShadowed() {
        return mIsShadowed;
    }

    public void setIsShadowed(final boolean isShadowed) {
        mIsShadowed = isShadowed;
        postInvalidate();
    }

    public float getShadowDistance() {
        return mShadowDistance;
    }

    public void setShadowDistance(final float shadowDistance) {
        mShadowDistance = shadowDistance;
        resetShadow();
    }

    public float getShadowAngle() {
        return mShadowAngle;
    }

    @SuppressLint("SupportAnnotationUsage")
    @FloatRange
    public void setShadowAngle(@FloatRange(from = MIN_ANGLE, to = MAX_ANGLE) final float shadowAngle) {
        mShadowAngle = Math.max(MIN_ANGLE, Math.min(shadowAngle, MAX_ANGLE));
        resetShadow();
    }

    public float getShadowRadius() {
        return mShadowRadius;
    }

    public void setShadowRadius(final float shadowRadius) {
        mShadowRadius = Math.max(MIN_RADIUS, shadowRadius);

        if (isInEditMode()) return;
        // Set blur filter to paint
        mPaint.setMaskFilter(new BlurMaskFilter(mShadowRadius, BlurMaskFilter.Blur.NORMAL));
        resetShadow();
    }

    public int getShadowColor() {
        return mShadowColor;
    }

    public void setShadowColor(final int shadowColor) {
        mShadowColor = shadowColor;
        mShadowAlpha = Color.alpha(shadowColor);

        resetShadow();
    }

    public float getShadowDx() {
        return mShadowDx;
    }

    public float getShadowDy() {
        return mShadowDy;
    }

    // Reset shadow layer
    private void resetShadow() {
        // Detect shadow axis offset
        mShadowDx = (float) ((mShadowDistance) * Math.cos(mShadowAngle / 180.0F * Math.PI));
        mShadowDy = (float) ((mShadowDistance) * Math.sin(mShadowAngle / 180.0F * Math.PI));

        // Set padding for shadow bitmap
        final int padding = (int) (mShadowDistance + mShadowRadius);
        setPadding(padding, padding, padding, padding);
        requestLayout();
    }

    private int adjustShadowAlpha(final boolean adjust) {
        return Color.argb(
                adjust ? MAX_ALPHA : mShadowAlpha,
                Color.red(mShadowColor),
                Color.green(mShadowColor),
                Color.blue(mShadowColor)
        );
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // Set ShadowLayout bounds
        mBounds.set(
                0, 0, MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)
        );
    }

    @Override
    public void requestLayout() {
        // Redraw shadow
        mInvalidateShadow = true;
        super.requestLayout();
    }

    @Override
    protected void dispatchDraw(final Canvas canvas) {
        // If is not shadowed, skip
        if (mIsShadowed) {
            // If need to redraw shadow
            if (mInvalidateShadow) {
                // If bounds is zero
                if (mBounds.width() != 0 && mBounds.height() != 0) {
                    // Reset bitmap to bounds
                    mBitmap = Bitmap.createBitmap(
                            mBounds.width(), mBounds.height(), Bitmap.Config.ARGB_8888
                    );
                    // Canvas reset
                    mCanvas.setBitmap(mBitmap);

                    // We just redraw
                    mInvalidateShadow = false;
                    // Main feature of this lib. We create the local copy of all content, so now
                    // we can draw bitmap as a bottom layer of natural canvas.
                    // We draw shadow like blur effect on bitmap, cause of setShadowLayer() method of
                    // paint does`t draw shadow, it draw another copy of bitmap
                    super.dispatchDraw(mCanvas);

                    // Get the alpha bounds of bitmap
                    final Bitmap extractedAlpha = mBitmap.extractAlpha();
                    // Clear past content content to draw shadow
                    mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);

                    // Draw extracted alpha bounds of our local canvas
                    mPaint.setColor(adjustShadowAlpha(false));
                    mCanvas.drawBitmap(extractedAlpha, mShadowDx, mShadowDy, mPaint);

                    // Recycle and clear extracted alpha
                    extractedAlpha.recycle();
                } else {
                    // Create placeholder bitmap when size is zero and wait until new size coming up
                    mBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);
                }
            }

            // Reset alpha to draw child with full alpha
            mPaint.setColor(adjustShadowAlpha(true));
            // Draw shadow bitmap
            if (mCanvas != null && mBitmap != null && !mBitmap.isRecycled())
                canvas.drawBitmap(mBitmap, 0.0F, 0.0F, mPaint);
        }

        // Draw child`s
        super.dispatchDraw(canvas);
    }


}

像这样在xml中使用Tag:

<yourpackagename.ShadowLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="center_horizontal"
        app:sl_shadow_color="#9e000000"
        app:sl_shadow_radius="4dp">
<child views>
</yourpackagename.ShadowLayout>

更新

将以下代码放在attrs.xml中的资源>>值中

  <declare-styleable name="ShadowLayout">
    <attr name="sl_shadowed" format="boolean"/>
    <attr name="sl_shadow_distance" format="dimension"/>
    <attr name="sl_shadow_angle" format="integer"/>
    <attr name="sl_shadow_radius" format="dimension"/>
    <attr name="sl_shadow_color" format="color"/>
</declare-styleable>

它将为任何视图提供阴影,希望它将对您
有用

@CoolMind我已经更新了R.styleable.ShadowLayout的代码。请检查我更新的答案
Shashwat Gupta,

感谢您的更新。我试图在API 19的仿真器上对其进行测试<TextView>,它使TextView居中,但未添加阴影。
CoolMind

有用。我认为需要sl_shadowed =“ true”,半径是填充,即阴影的宽度,距离和角度使dx,dy偏移。我想应该添加的是这样的东西//为阴影位图设置填充val padding =(shadowDistance + shadowRadius).toInt()setPadding(if(shadowLeft)填充else 0,if(shadowTop)填充else 0,if(shadowRight )填充否则为0,如果(shadowBottom)填充否则为0)然后可以在阴影有条件地打开布局的优选边缘
米哈尔Ziobro

0

一种可能的解决方案是使用九个补丁映像,例如 http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

要么

我已经通过以下方式做到了。这是我的主要布局,其中round_corner.xml和drop_shadow.xml用作背景资源。round_corner_two与round_corner.xml相同,只是color属性不同。将round_corner.xml,drop_shadow.xml和round_conere_two.xml复制到可绘制文件夹中。

<RelativeLayout
    android:id="@+id/facebook_id"
    android:layout_width="250dp"
    android:layout_height="52dp"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="28dp"
    android:background="@drawable/round_corner" >

    <LinearLayout
        android:id="@+id/shadow_id"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_margin="1dp"
        android:background="@drawable/drop_shadow" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_marginBottom="2dp"
            android:background="@drawable/round_corner_two"
            android:gravity="center"
            android:text="@string/fb_butn_text"
            android:textColor="@color/white" >
        </TextView>
    </LinearLayout>
</RelativeLayout>

round_corner.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<!-- view background color -->
<solid
    android:color="#ffffff" >
</solid>

<!-- view border color and width -->
<stroke
    android:width="0dp"
    android:color="#3b5998" >
</stroke>

<!-- If you want to add some padding -->
<padding
    android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp"    >
</padding>

<!-- Here is the corner radius -->
<corners
    android:radius="10dp"   >
</corners>

</shape>

drop_shadow.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
    <shape 
        android:shape="rectangle">
    <solid android:color="@android:color/darker_gray" />
    <corners android:radius="12dp"/>
    </shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="5dp">
    <shape 
        android:shape="rectangle">
    <solid android:color="@android:color/white"/>
    <corners android:radius="5dp"/>
    </shape>
</item>
</layer-list>

0

我知道这太晚了。但我有同样的要求。我这样解决了

<android.support.v7.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardUseCompatPadding="true"
app:cardElevation="4dp"
app:cardCornerRadius="3dp" >

<!-- put whatever you want -->

</android.support.v7.widget.CardView>

您需要添加依赖项:

compile 'com.android.support:cardview-v7:25.0.1'

-1

将此xml drwable设置为背景; ---

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- Bottom 2dp Shadow -->
<item>
    <shape android:shape="rectangle" >
        <solid android:color="#d8d8d8" />-->Your shadow color<--

        <corners android:radius="15dp" />
    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px" android:left="3px" android:right="3px" android:top="3px">-->here you can customize the shadow size<---
    <shape android:shape="rectangle" >
        <solid android:color="#FFFFFF" />

        <corners android:radius="15dp" />
    </shape>
</item>

</layer-list>

这会给文本(而不是布局)阴影。
Abhinav Manchanda

3
不,它不会显示阴影。您能否提供更详细的答案?
Yi H.
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.