微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在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"

原文地址:https://www.jb51.cc/android/313071.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐