如何在Android API中模拟低于21的按钮高程(阴影)?

我只用一个按钮就可以实现这个最小的 Android Studio项目.
我为按钮指定了一个阴影:
android:elevation="3dp"
android:translationZ="3dp"
android:stateListAnimator="@null"

我在Android Studio Design标签中看到了阴影.但我也在xml编辑器中收到警告

Atribute … is only used in API level 21 and higher (current min is 16)

实际上,按钮阴影仅在API级别为21或更高的模拟器中显示,并且显示为平面,在API级别低于21的模拟器中完全没有阴影.

所以具体问题是,如何在API低于21的情况下模拟阴影效果.

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:id="@+id/main_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:weightSum="1">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dp"
            android:layout_weight="2.24">

            <Button
                android:id="@+id/my_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="20dp"
                android:layout_marginBottom="20dp"
                android:elevation="5dp"
                android:translationZ="5dp"
                android:stateListAnimator="@null"
                android:background="@android:color/holo_green_light"
                android:text="BUTTON"/>

        </RelativeLayout>
    </LinearLayout>
</ScrollView>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

}

在API 22中显示阴影的按钮:

在API 16中,相同的按钮不显示阴影:

解决方法

对于Pre-LolliPop设备,您必须使用可绘制文件创建阴影或高程.这条路.

在您的文件夹中创建可绘制文件,如element_background.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="#BDBDBD"/>
        <corners android:radius="5dp"/>
    </shape>
</item>

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

然后将以下代码添加到您想要的元素.

android:background="@drawable/element_background"

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...