一、概述
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。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/258064.html