首页 > 笔记大全 > 详解android:elevation的使用

详解android:elevation的使用

更新:

一、概述

android:elevation是Android启用新的Material Design的重要属性之一。增加这个属性能够在视图上添加阴影效果,提升了UI效果和用户体验。在本文中,我们将详细讨论Android的android:elevation,如何使用它以及如何将其应用于不同的控件和布局。

二、如何使用android:elevation

android:elevation是Android 5.0(API 21)中新增的一个属性,它的值表示视图距离Z轴平面的距离。可以通过在XML布局文件中添加android:elevation属性来设置视图的高度。例如:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp"
    android:text="Button"/>

这个Button现在会在Z轴上处于比其他视图更高的位置,并使用4dp的距离添加阴影效果。

三、android:elevation与阴影效果

android:elevation属性提供了在Android应用程序中实现阴影效果的一种简单方法。使用此属性可以为控件添加立体效果,从而使控件看起来更加现代化。可以为单个视图添加阴影效果,还可以将多个视图组合成单个阴影效果。

要在视图中添加阴影效果,只需在布局文件中添加android:elevation属性。例如:

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp"
    android:text="Button"/>

在这个简单的示例中,Button会显示一个高度为4dp的阴影效果。

四、android:elevation和Z轴

android:elevation属性是基于Z轴的,这意味着视图将在Z轴上移动,根据这个值进行层次分配。如果两个视图有不同的Z轴高度,则具有更高Z轴高度的视图将覆盖具有较低Z轴高度的视图。

为了演示此功能,请考虑下面的布局文件:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="4dp"
        android:text="Button 1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:elevation="8dp"
        android:text="Button 2"/>

</LinearLayout>

在这个例子中,第一个Button视图的高度设置为4dp,第二个Button视图的高度设置为8dp。由于第二个Button视图的高度更高,它将显示在第一个Button视图的顶部。

五、android:elevation和CardView

在使用CardView时,android:elevation特别有用。相应的,Cardview具有添加阴影效果和圆角的功能。

要使用android:elevation和CardView,请按照下面的代码示例进行设置:

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="6dp"
    app:cardCornerRadius="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="这是标题"
            android:textAppearance="@android:style/TextAppearance.Large"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="这是内容"
            android:textAppearance="@android:style/TextAppearance.Medium"/>

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

在这个例子中,我们为CardView添加了6dp的android:elevation,而app:cardCornerRadius设置了圆角的大小。这将创建一个具有阴影效果和圆角的CardView。

文章目录
顶部