如何在Android 5.0以下版本中实现Material Design的高度效果

44

谷歌在Lollipop上展示了一些漂亮的高程效果,此处有相关内容。

android:elevation="2dp"

对于按钮,

android:stateListAnimator="@anim/button_state_list_animator"

如何在没有第三方库的情况下模拟早期版本上的海拔效果?


1
您可以使用应用程序中的自定义库来完成此操作。您可以在以下链接中找到示例:https://github.com/wasabeef/awesome-android-ui - Rajan Bhavsar
@RajanBhavsar 我可以不使用第三方库来实现吗? - AndroidDev
是的,请点击此链接http://arjunu.com/2015/02/materializing-your-apps-for-pre-lollipop/进行操作。 - Rajan Bhavsar
1
你可以尝试这个:https://dev59.com/AV8d5IYBdhLWcg3wiSjI#26747592 - YenMinh
可能是Android视图阴影的重复问题。 - Peter O.
7个回答

82

如果我想使用一个蓝色背景的按钮怎么办? - Adnan Ali
如何使用此方法自定义高程值 - kundan roy

22

使用官方方法无法模拟Lollipop以前的高程。

您可以在组件中使用一些可绘制对象来创建阴影。例如,Google在CardView中使用了这种方式。

ViewCompat.setElevation (View,int)目前仅在API 21+上创建阴影。如果您检查其背后的代码,该方法调用:

API 21+:

  @Override
    public void setElevation(View view, float elevation) {
        ViewCompatLollipop.setElevation(view, elevation);
    }

API小于21

@Override
public void setElevation(View view, float elevation) {

}

15

你可以使用卡片视图进行黑客攻击:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/btnGetStuff"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardBackgroundColor="@color/accent"
    >
    <!-- you could also add image view here for icon etc. -->
    <TextView
        android:id="@+id/txtGetStuff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/textSize_small"
        android:textColor="@color/primary_light"
        android:freezesText="true"
        android:text="Get Stuff"
        android:maxWidth="120dp"
        android:singleLine="true"
        android:ellipsize="end"
        android:maxLines="1"
        /></android.support.v7.widget.CardView>

或者考虑使用这个第三方库:https://github.com/rey5137/Material(查看按钮的 wiki 文章:https://github.com/rey5137/Material/wiki/Button


10

要在安卓Lollipop版本以下的设备上实现动态的、带有动画效果的阴影,需要进行以下步骤:

  1. 将一个视图绘制成黑色的形状,并转换成位图
  2. 使用高度作为模糊半径对该形状进行模糊处理。可以使用RenderScript来实现。虽然这不是Lollipop版本所采用的方法,但是可以得到良好的结果,并且易于应用到现有视图中。
  3. 在视图下方绘制那个模糊的形状。最好的地方可能是drawChild 方法。还需要重写setElevationsetTranslationZ,在布局中覆盖子视图绘制,关闭裁剪填充并实现状态动画。

enter image description here

虽然这需要很多工作,但它可以实现看起来最好的动态阴影和响应动画。如果您愿意,您可以分析Carbon的源代码并移植其中的部分到您的应用程序中:

Shadow generation

private static void blurRenderScript(Bitmap bitmap, float radius) {
    Allocation inAllocation = Allocation.createFromBitmap(renderScript, bitmap,
            Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    Allocation outAllocation = Allocation.createTyped(renderScript, inAllocation.getType());

    blurShader.setRadius(radius);
    blurShader.setInput(inAllocation);
    blurShader.forEach(outAllocation);

    outAllocation.copyTo(bitmap);
}

public static Shadow generateShadow(View view, float elevation) {
    if (!software && renderScript == null) {
        try {
            renderScript = RenderScript.create(view.getContext());
            blurShader = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        } catch (RSRuntimeException ignore) {
            software = true;
        }
    }

    ShadowView shadowView = (ShadowView) view;
    CornerView cornerView = (CornerView) view;
    boolean isRect = shadowView.getShadowShape() == ShadowShape.RECT ||
            shadowView.getShadowShape() == ShadowShape.ROUND_RECT && cornerView.getCornerRadius() < view.getContext().getResources().getDimension(R.dimen.carbon_1dip) * 2.5;

    int e = (int) Math.ceil(elevation);
    Bitmap bitmap;
    if (isRect) {
        bitmap = Bitmap.createBitmap(e * 4 + 1, e * 4 + 1, Bitmap.Config.ARGB_8888);

        Canvas shadowCanvas = new Canvas(bitmap);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xff000000);

        shadowCanvas.drawRect(e, e, e * 3 + 1, e * 3 + 1, paint);

        blur(bitmap, elevation);

        return new NinePatchShadow(bitmap, elevation);
    } else {
        bitmap = Bitmap.createBitmap((int) (view.getWidth() / SHADOW_SCALE + e * 2), (int) (view.getHeight() / SHADOW_SCALE + e * 2), Bitmap.Config.ARGB_8888);

        Canvas shadowCanvas = new Canvas(bitmap);
        paint.setStyle(Paint.Style.FILL);
        paint.setColor(0xff000000);

        if (shadowView.getShadowShape() == ShadowShape.ROUND_RECT) {
            roundRect.set(e, e, (int) (view.getWidth() / SHADOW_SCALE - e), (int) (view.getHeight() / SHADOW_SCALE - e));
            shadowCanvas.drawRoundRect(roundRect, e, e, paint);
        } else {
            int r = (int) (view.getWidth() / 2 / SHADOW_SCALE);
            shadowCanvas.drawCircle(r + e, r + e, r, paint);
        }

        blur(bitmap, elevation);

        return new Shadow(bitmap, elevation);
    }
}

如何绘制带阴影的视图

@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    if (!child.isShown())
        return super.drawChild(canvas, child, drawingTime);

    if (!isInEditMode() && child instanceof ShadowView && Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) {
        ShadowView shadowView = (ShadowView) child;
        Shadow shadow = shadowView.getShadow();
        if (shadow != null) {
            paint.setAlpha((int) (ShadowGenerator.ALPHA * ViewHelper.getAlpha(child)));

            float childElevation = shadowView.getElevation() + shadowView.getTranslationZ();

            float[] childLocation = new float[]{(child.getLeft() + child.getRight()) / 2, (child.getTop() + child.getBottom()) / 2};
            Matrix matrix = carbon.internal.ViewHelper.getMatrix(child);
            matrix.mapPoints(childLocation);

            int[] location = new int[2];
            getLocationOnScreen(location);
            float x = childLocation[0] + location[0];
            float y = childLocation[1] + location[1];
            x -= getRootView().getWidth() / 2;
            y += getRootView().getHeight() / 2;   // looks nice
            float length = (float) Math.sqrt(x * x + y * y);

            int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
            canvas.translate(
                    x / length * childElevation / 2,
                    y / length * childElevation / 2);
            canvas.translate(
                    child.getLeft(),
                    child.getTop());

            canvas.concat(matrix);
            canvas.scale(ShadowGenerator.SHADOW_SCALE, ShadowGenerator.SHADOW_SCALE);
            shadow.draw(canvas, child, paint);
            canvas.restoreToCount(saveCount);
        }
    }

    if (child instanceof RippleView) {
        RippleView rippleView = (RippleView) child;
        RippleDrawable rippleDrawable = rippleView.getRippleDrawable();
        if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless) {
            int saveCount = canvas.save(Canvas.MATRIX_SAVE_FLAG);
            canvas.translate(
                    child.getLeft(),
                    child.getTop());
            rippleDrawable.draw(canvas);
            canvas.restoreToCount(saveCount);
        }
    }

    return super.drawChild(canvas, child, drawingTime);
}

将 Elevation API 回溯到 Android 5.0 之前的版本

private float elevation = 0;
private float translationZ = 0;
private Shadow shadow;

@Override
public float getElevation() {
    return elevation;
}

public synchronized void setElevation(float elevation) {
    if (elevation == this.elevation)
        return;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        super.setElevation(elevation);
    this.elevation = elevation;
    if (getParent() != null)
        ((View) getParent()).postInvalidate();
}

@Override
public float getTranslationZ() {
    return translationZ;
}

public synchronized void setTranslationZ(float translationZ) {
    if (translationZ == this.translationZ)
        return;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        super.setTranslationZ(translationZ);
    this.translationZ = translationZ;
    if (getParent() != null)
        ((View) getParent()).postInvalidate();
}

@Override
public ShadowShape getShadowShape() {
    if (cornerRadius == getWidth() / 2 && getWidth() == getHeight())
        return ShadowShape.CIRCLE;
    if (cornerRadius > 0)
        return ShadowShape.ROUND_RECT;
    return ShadowShape.RECT;
}

@Override
public void setEnabled(boolean enabled) {
    super.setEnabled(enabled);
    setTranslationZ(enabled ? 0 : -elevation);
}

@Override
public Shadow getShadow() {
    float elevation = getElevation() + getTranslationZ();
    if (elevation >= 0.01f && getWidth() > 0 && getHeight() > 0) {
        if (shadow == null || shadow.elevation != elevation)
            shadow = ShadowGenerator.generateShadow(this, elevation);
        return shadow;
    }
    return null;
}

@Override
public void invalidateShadow() {
    shadow = null;
    if (getParent() != null && getParent() instanceof View)
        ((View) getParent()).postInvalidate();
}

Elevation API的指向File Line的链接从昨天开始更新。因此,请您提供一小段代码,以便开发人员更好地了解实际代码。 - DearDhruv

8

创建一个9-patch图像,该图像在周围具有阴影,并定义了可拉伸补丁。

enter image description here

将此九宫格图像作为按钮的背景,并添加填充以使阴影可见。

您可以在此处此处找到一些预定义的九宫格(.9.png)图像,从中选择、自定义并复制到您项目的drawable文件夹中。


6

为了给可绘制对象添加背景颜色(例如按钮背景颜色),我们需要以编程方式获取可绘制对象。

首先获取可绘制对象。

Drawable drawable = getResources().getDrawable(android.R.drawable.dialog_holo_light_frame);

设置颜色

drawable.setColorFilter(new PorterDuffColorFilter(getResources().getColor(R.color.color_primary), PorterDuff.Mode.MULTIPLY));

然后将其设置到视图中。
view.setBackgroundDrawable(drawable);

如果有人在搜索相关内容。


2
您可以通过声明类似于以下方式的可绘制对象轻松模拟它 -

shadow.xml

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

    >

    <gradient android:type="linear" android:angle="270" android:startColor="#b6b6b6" android:endColor="#ffffff"/>


</shape>

并在主XML文件中使用它,例如 -

 android:background="@drawable/shadow"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接