Xamarin CardViewXamarin.Android CardView

Cardview 小组件是一个 UI 组件,用于在类似卡片的视图中提供文本和图像内容。本指南说明如何在 Xamarin Android 应用程序中使用和自定义 CardView,同时保持与早期版本的 Android 的向后兼容性。The Cardview widget is a UI component that presents text and image content in views that resemble cards. This guide explains how to use and customize CardView in Xamarin.Android applications while maintaining backward compatibility with earlier versions of Android.

概述Overview

Android 5.0 (棒糖形)中引入的 Cardview 小组件是一个 UI 组件,用于在类似卡片的视图中提供文本和图像内容。The Cardview widget, introduced in Android 5.0 (Lollipop), is a UI component that presents text and image content in views that resemble cards. CardView 作为带有圆角和阴影的 FrameLayout 小组件实现。CardView is implemented as a FrameLayout widget with rounded corners and a shadow. 通常,CardView 用于在 ListViewGridView 视图组中显示单个行项。Typically, a CardView is used to present a single row item in a ListView or GridView view group. 例如,以下屏幕截图是在可滚动的 ListView中实现基于 CardView的旅游目标卡的旅行预订应用程序的一个示例:For example, the following screen shot is an example of a travel reservation app that implements CardView-based travel destination cards in a scrollable ListView:

为每个旅行目标使用 CardView 的示例应用

本指南说明如何将 CardView 包添加到你的 Xamarin Android 项目,如何将 CardView 添加到你的布局中,以及如何在你的应用程序中自定义 CardView 的外观。This guide explains how to add the CardView package to your Xamarin.Android project, how to add CardView to your layout, and how to customize the appearance of CardView in your app. 此外,本指南还提供了可以更改的 CardView 属性的详细列表,其中包括一些属性,可帮助您在早于 Android 5.0 棒糖的 Android 版本上使用 CardViewIn addition, this guide provides a detailed list of CardView attributes that you can change, including attributes to help you use CardView on versions of Android earlier than Android 5.0 Lollipop.

要求Requirements

在基于 Xamarin 的应用中使用新的 Android 5.0 及更高版本功能(包括 CardView)时,需要满足以下要求:The following is required to use new Android 5.0 and later features (including CardView) in Xamarin-based apps:

  • Xamarin – xamarin 4.20 或更高版本必须安装并配置 Visual Studio 或 Visual Studio for Mac。Xamarin.Android – Xamarin.Android 4.20 or later must be installed and configured with either Visual Studio or Visual Studio for Mac.

  • 必须通过 Android SDK 管理器安装Android SDK – Android 5.0 (API 21)或更高版本。Android SDK – Android 5.0 (API 21) or later must be installed via the Android SDK Manager.

  • 如果专门针对 API 级别23和更早版本,可以使用JAVA jdk 1.8 – JDK 1.7。Java JDK 1.8 – JDK 1.7 can be used if you are specifically targetting API level 23 and earlier. JDK 1.8 可从Oracle获得。JDK 1.8 is available from Oracle.

应用还必须包含 Xamarin.Android.Support.v7.CardView 包。Your app must also include the Xamarin.Android.Support.v7.CardView package. 若要在 Visual Studio for Mac 中添加 Xamarin.Android.Support.v7.CardView 包:To add the Xamarin.Android.Support.v7.CardView package in Visual Studio for Mac:

  1. 打开项目,右键单击 "",然后选择 "添加包"。Open your project, right-click Packages and select Add Packages.

  2. 在 "添加包" 对话框中,搜索 " CardView"。In the Add Packages dialog, search for CardView.

  3. 选择 " Xamarin 支持库 V7 CardView",并单击 "添加包"。Select Xamarin Support Library v7 CardView, then click Add Package.

若要在 Visual Studio 中添加 Xamarin.Android.Support.v7.CardView 包:To add the Xamarin.Android.Support.v7.CardView package in Visual Studio:

  1. 打开项目,右键单击 "引用" 节点(在 "解决方案资源管理器" 窗格中),然后选择 "管理 NuGet 包 ... "。Open your project, right-click the References node (in the Solution Explorer pane) and select Manage NuGet Packages....

  2. 显示 "管理 NuGet 包" 对话框时,请在 "搜索" 框中输入CardViewWhen the Manage NuGet Packages dialog is displayed, enter CardView in the search box.

  3. 出现 " Xamarin 支持库 V7 CardView " 时,单击 "安装"。When Xamarin Support Library v7 CardView appears, click Install.

若要了解如何配置 Android 5.0 应用项目,请参阅设置 android 5.0 项目To learn how to configure an Android 5.0 app project, see Setting Up an Android 5.0 Project. 有关安装 NuGet 包的详细信息,请参阅演练:在项目中包括 NuGetFor more information about installing NuGet packages, see Walkthrough: Including a NuGet in your project.

CardView 简介Introducing CardView

默认 CardView 类似于具有最小圆角和轻微阴影的白色卡片。The default CardView resembles a white card with minimally rounded corners and a slight shadow. 下面的示例main.axml布局显示了包含 TextView的单个 CardView 小组件:The following example Main.axml layout displays a single CardView widget that contains a TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:padding="5dp">
    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="245dp"
        android:layout_gravity="center_horizontal">
        <TextView
            android:text="Basic CardView"
            android:layout_marginTop="0dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </android.support.v7.widget.CardView>
</LinearLayout>

如果你使用此 XML 来替换main.axml的现有内容,请确保注释掉引用前面 XML 中的资源的MainActivity.cs中的任何代码。If you use this XML to replace the existing contents of Main.axml, be sure to comment out any code in MainActivity.cs that refers to resources in the previous XML.

此布局示例创建一个默认的 CardView,其中包含一行文本,如以下屏幕截图所示:This layout example creates a default CardView with a single line of text as shown in the following screen shot:

用白色背景和文本行CardView 屏幕截图Screenshot of CardView with white background and line of text

在此示例中,应用样式设置为光源材料主题(Theme.Material.Light),以便更易于查看 CardView 阴影和边缘。In this example, the app style is set to the light Material Theme (Theme.Material.Light) so that the CardView shadows and edges are easier to see. 有关主题 Android 5.0 应用的详细信息,请参阅材料主题For more information about theming Android 5.0 apps, see Material Theme. 在下一部分中,我们将了解如何为应用程序自定义 CardViewIn the next section, we'll learn how to customize CardView for an application.

自定义 CardViewCustomizing CardView

您可以修改基本 CardView 属性,以自定义应用程序中 CardView 的外观。You can modify the basic CardView attributes to customize the appearance of the CardView in your app. 例如,可以增加 CardView 的提升量来强制转换较大的阴影(这使得卡片看起来更大的背景)。For example, the elevation of the CardView can be increased to cast a larger shadow (which makes the card seem to float higher above the background). 另外,还可以增加角半径,使纸牌的拐角更大一些。Also, the corner radius can be increased to make the corners of the card more rounded.

在下一个布局示例中,自定义的 CardView 用于创建打印照片("快照")的模拟。In the next layout example, a customized CardView is used to create a simulation of a print photograph (a "snapshot"). ImageView 将添加到用于显示图像的 CardView 中,TextView 定位在用于显示图像标题的 ImageView 下。An ImageView is added to the CardView for displaying the image, and a TextView is positioned below the ImageView for displaying the title of the image. 在此示例布局中,CardView 具有下列自定义项:In this example layout, the CardView has the following customizations:

  • cardElevation 增加到4dp,以转换更大的阴影。The cardElevation is increased to 4dp to cast a larger shadow.
  • cardCornerRadius 增加到5dp,以使拐角显得更大。The cardCornerRadius is increased to 5dp to make the corners appear more rounded.

由于 Android v7 支持库提供 CardView,因此 android: 命名空间中不提供其属性。Because CardView is provided by the Android v7 support library, its attributes are not available from the android: namespace. 因此,你必须定义自己的 XML 命名空间,并使用该命名空间作为 CardView 特性前缀。Therefore, you must define your own XML namespace and use that namespace as the CardView attribute prefix. 在下面的布局示例中,将使用此行定义名为 cardview的命名空间:In the layout example below, we will use this line to define a namespace called cardview:

    xmlns:cardview="http://schemas.android.com/apk/res-auto"

您可以调用此命名空间 card_view 甚至 myapp (如果选择)(只能在此文件的作用域内访问)。You can call this namespace card_view or even myapp if you choose (it's accessible only within the scope of this file). 无论你选择调用此命名空间,你都必须使用它为你要修改的 CardView 属性加上前缀。Whatever you choose to call this namespace, you must use it to prefix the CardView attribute that you want to modify. 在此布局示例中,cardview 命名空间是 cardElevationcardCornerRadius的前缀:In this layout example, the cardview namespace is the prefix for cardElevation and cardCornerRadius:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardview="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:padding="5dp">
    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="245dp"
        android:layout_gravity="center_horizontal"
        cardview:cardElevation="4dp"
        cardview:cardCornerRadius="5dp">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="240dp"
            android:orientation="vertical"
            android:padding="8dp">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="190dp"
                android:id="@+id/imageView"
                android:scaleType="centerCrop" />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#333333"
                android:text="Photo Title"
                android:id="@+id/textView"
                android:layout_gravity="center_horizontal"
                android:layout_marginLeft="5dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

当此布局示例用于显示照片查看应用中的图像时,CardView 具有照片快照的外观,如以下屏幕截图所示:When this layout example is used to display an image in a photo viewing app, the CardView has the appearance of a photo snapshot, as depicted in the following screenshot:

在图像下方使用图像和标题CardViewCardView with an image and caption below the image

此屏幕截图取自RecyclerViewer示例应用程序,该应用程序使用 RecyclerView 小组件提供用于查看照片的 CardView 图像的滚动列表。This screenshot is taken from the RecyclerViewer sample app, which uses a RecyclerView widget to present a scrolling list of CardView images for viewing photos. 有关 RecyclerView的详细信息,请参阅RecyclerView指南。For more information about RecyclerView, see the RecyclerView guide.

请注意,CardView 可以在其内容区域中显示一个以上的子视图。Notice that a CardView can display more than one child view in its content area. 例如,在上述照片查看应用程序示例中,内容区域由包含 ImageViewTextViewListView 组成。For example, in the above photo viewing app example, the content area is comprised of a ListView that contains an ImageView and a TextView. 尽管 CardView 实例通常是垂直排列的,但您也可以水平排列它们(有关示例屏幕截图,请参阅创建自定义视图样式)。Although CardView instances are often arranged vertically, you can also arrange them horizontally (see Creating a Custom View Style for an example screenshot).

CardView 布局选项CardView Layout Options

可以通过设置一个或多个属性来自定义 CardView 布局,这些特性会影响其填充、仰角、角半径和背景色:CardView layouts can be customized by setting one or more attributes that affect its padding, elevation, corner radius, and background color:

CardView 特性关系图Diagram of CardView attributes

还可以通过调用与 CardView 方法对应的方法,动态更改每个特性(有关 CardView 方法的详细信息,请参阅CardView 类引用)。Each attribute can also be changed dynamically by calling a counterpart CardView method (for more information on CardView methods, see the CardView class reference). 请注意,这些属性(背景颜色除外)接受一个维度值,该值是一个十进制数,后跟单位。Note that these attributes (except for background color) accept a dimension value, which is a decimal number followed by the unit. 例如,11.5dp 指定11.5 与密度无关的像素。For example, 11.5dp specifies 11.5 density-independent pixels.

填充Padding

CardView 提供五个填充属性来定位卡片内的内容。CardView offers five padding attributes to position content within the card. 可以在布局 XML 中进行设置,也可以在代码中调用类似的方法:You can set them in your layout XML or you can call analogous methods in your code:

CardView 填充特性关系图Diagram of CardView padding attributes

填充属性如下所述:The padding attributes are explained as follows:

  • contentPaddingCardView 的子视图和卡片的所有边缘之间的内部填充。contentPadding – Inner padding between the child views of the CardView and all edges of the card.

  • contentPaddingBottomCardView 的子视图与卡的下边缘之间的内部填充。contentPaddingBottom – Inner padding between the child views of the CardView and the bottom edge of the card.

  • contentPaddingLeftCardView 的子视图与卡片左边缘之间的内部填充。contentPaddingLeft – Inner padding between the child views of the CardView and the left edge of the card.

  • contentPaddingRightCardView 的子视图与卡片的右边缘之间的内部填充。contentPaddingRight – Inner padding between the child views of the CardView and the right edge of the card.

  • contentPaddingTopCardView 的子视图与卡片上边缘之间的内部填充。contentPaddingTop – Inner padding between the child views of the CardView and the top edge of the card.

内容填充属性相对于内容区域的边界,而不是相对于内容区域内的任何给定小组件。Content padding attributes are relative to the boundary of the content area rather than to any given widget located within the content area. 例如,如果在照片查看应用中充分增加了 contentPadding,则 CardView 会裁剪图像和卡片上显示的文本。For example, if contentPadding were sufficiently increased in the photo viewing app, the CardView would crop both the image and the text shown on the card.

仰角Elevation

CardView 提供了两个提升特性来控制其提升,因此,其阴影的大小为:CardView offers two elevation attributes to control its elevation and, as a result, the size of its shadow:

CardView 提升特性关系图Diagram of CardView elevation attributes

提升属性如下所述:The elevation attributes are explained as follows:

  • cardElevationCardView 的仰角(表示其 Z 轴)。cardElevation – The elevation of the CardView (represents its Z axis).

  • cardMaxElevationCardView提升的最大值。cardMaxElevation – The maximum value of the CardView's elevation.

cardElevation 的值越大,就会增加阴影大小,使其看起来 CardView 在背景上方更高。Larger values of cardElevation increase the shadow size to make CardView seem to float higher above the background. cardElevation 属性还确定了重叠视图的绘制顺序;也就是说,CardView 将在另一个具有较高提升设置的重叠视图下绘制,并在具有较低提升设置的任何重叠视图上绘制。The cardElevation attribute also determines the drawing order of overlapping views; that is, the CardView will be drawn under another overlapping view with a higher elevation setting and above any overlapping views with a lower elevation setting. 当应用动态更改提升时,cardMaxElevation 设置非常有用 – 它会阻止阴影超出你用此设置定义的限制。The cardMaxElevation setting is useful for when your app changes elevation dynamically – it prevents the shadow from extending past the limit that you define with this setting.

角半径和背景色Corner Radius and Background Color

CardView 提供了可用于控制其角半径及其背景色的特性。CardView offers attributes that you can use to control its corner radius and its background color. 这两个属性允许您更改 CardView的总体样式:These two properties allow you change the overall style of the CardView:

CardView 角 radious 和背景色属性的图示Diagram of CardView corner radious and background color attributes

这些属性的解释如下:These attributes are explained as follows:

  • cardCornerRadiusCardView所有拐角的角半径。cardCornerRadius – The corner radius of all corners of the CardView.

  • cardBackgroundColorCardView的背景色。cardBackgroundColor – The background color of the CardView.

在此图中,将 cardCornerRadius 设置为更大的10dp,并将 cardBackgroundColor 设置为 "#FFFFCC" (浅黄色)。In this diagram, cardCornerRadius is set to a more rounded 10dp and cardBackgroundColor is set to "#FFFFCC" (light yellow).

兼容性Compatibility

可以在 android 5.0 以前版本的 Android 上使用 CardViewYou can use CardView on versions of Android earlier than Android 5.0 Lollipop. 由于 CardView 是 Android v7 支持库的一部分,因此可以使用适用于 Android 2.1 (API 级别7)和更高版本的 CardViewBecause CardView is part of the Android v7 support library, you can use CardView with Android 2.1 (API level 7) and higher. 但是,必须按照上面的要求中所述安装 Xamarin.Android.Support.v7.CardView 包。However, you must install the Xamarin.Android.Support.v7.CardView package as described in Requirements, above.

在棒糖形之前,CardView 在设备上出现略微不同的行为(API 级别21):CardView exhibits slightly different behavior on devices before Lollipop (API level 21):

  • CardView 使用添加附加填充的编程阴影实现。CardView uses a programmatic shadow implementation that adds additional padding.

  • CardView 不会剪裁与 CardView圆角相交的子视图。CardView does not clip child views that intersect with the CardView's rounded corners.

为了帮助管理这些兼容性差异,CardView 提供了可在布局中配置的几个附加属性:To help in managing these compatibility differences, CardView provides several additional attributes that you can configure in your layout:

  • cardPreventCornerOverlap – 将此特性设置为 true,以便在应用程序在早期 Android 版本(API 级别20和更早版本)上运行时添加填充。cardPreventCornerOverlap – Set this attribute to true to add padding when your app is running on earlier Android versions (API level 20 and earlier). 此设置可防止 CardView 内容与 CardView的圆角相交。This setting prevents CardView content from intersecting with the CardView's rounded corners.

  • cardUseCompatPadding – 将此特性设置为 true,以便在应用程序运行时,在 Android 版本或大于 API 级别21时添加填充。cardUseCompatPadding – Set this attribute to true to add padding when your app is running in versions of Android at or greater than API level 21. 如果要在棒糖形设备上使用 CardView,并使其在棒糖形(或更高版本)上看起来相同,请将此属性设置为 trueIf you want to use CardView on pre-Lollipop devices and have it look the same on Lollipop (or later), set this attribute to true. 如果启用此属性,则 CardView 在运行于棒糖的设备上时,添加用于绘制阴影的附加填充。When this attribute is enabled, CardView adds additional padding to draw shadows when it runs on pre-Lollipop devices. 这有助于克服当棒式编程影子实现生效时所引入的填充的差别。This helps to overcome the differences in padding that are introduced when pre-Lollipop programmatic shadow implementations are in effect.

有关保持与早期版本的 Android 兼容性的详细信息,请参阅维护兼容性For more information about maintaining compatibility with earlier versions of Android, see Maintaining Compatibility.

总结Summary

本指南介绍 Android 5.0 (棒糖形)中包含的新 CardView 小组件。This guide introduced the new CardView widget included in Android 5.0 (Lollipop). 它演示了默认 CardView 外观,并说明了如何通过更改其提升、角圆度、内容填充和背景色自定义 CardViewIt demonstrated the default CardView appearance and explained how to customize CardView by changing its elevation, corner roundness, content padding, and background color. 它列出了 CardView 布局特性(包含引用关系图),并说明了如何在 android 5.0 棒糖之前的 Android 设备上使用 CardViewIt listed the CardView layout attributes (with reference diagrams), and explained how to use CardView on Android devices earlier than Android 5.0 Lollipop. 有关 CardView的详细信息,请参阅CardView 类参考For more information about CardView, see the CardView class reference.