在Android L中如何在CardView中显示UI小部件

6
我将尝试创建一个卡片视图应用程序,其中卡片视图包含两个文本视图,需要并排放置,但是文本视图重叠了。是否有一种机制可以像 RelativeLayout(layout_below 或 layout_toRightOf)那样放置元素到 Cardviews 中?
我能通过在 RelativeLayout 中添加阴影并使其看起来像 Cardview 来实现此功能,但我想在 Cardview 中实现这一点。
以下是我的布局代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@android:color/black"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:background="@color/white"
        android:layout_width="200dp"
        android:layout_height="200dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Textview one"
            android:gravity="center"
            android:textSize="36sp" />
        <TextView
            android:id="@+id/info_text1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Textview two"
            android:gravity="center"
            android:textSize="36sp" />
    </android.support.v7.widget.CardView>
</RelativeLayout>

目前显示的样式如附图所示: “输入图像描述”src
1个回答

17

根据CardView的描述:

CardView 扩展了FrameLayout类,允许您在具有一致外观的卡片中显示信息。CardView小部件可以具有阴影和圆角。

如您所知,在FrameLayout中没有视图定位之间的任何约束或关系。他们将一个接一个地显示。如果您想在CardView内使用不同的层次结构,请在内部使用任何布局即可。例如:

<android.support.v7.widget.CardView
    android:id="@+id/card_view"
    android:background="@color/white"
    android:layout_width="200dp"
    android:layout_height="200dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview one"
            android:gravity="center"
            android:textSize="36sp" />
        <TextView
            android:id="@+id/info_text1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Textview two"
            android:gravity="center"
            android:textSize="36sp" />
    </LinearLayout>

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

CardView 仅视为外部装饰,您可以在内部使用任何布局。因此,如果 LinearLayout 不适用,您可以使用 RelativeLayout 等。


正如我在问题中提到的那样,我可以通过将cardview的内容嵌入布局中来实现。但是我正在寻找不这样做的选项,因为它们很昂贵。 - Psypher
你写道:“我可以通过向RelativeLayout添加阴影并使其看起来像CardView来实现这一点”,这基本上意味着你能够使用RelativeLayout“模仿”CardView,并向其中添加阴影,而不是你知道你可以在其中添加RelativeLayout :) 但好吧。所以你有两个解决方案:1.像我在答案中建议的那样使用内部布局;2.扩展CardView并在自己的自定义测量和布局方法上实现(就像你创建自定义布局并从代码中定位子项的方式一样)。没有其他方法可以做到这一点。 - Maciej Ciemięga
据我所知,您无法扩展CardView。 - mDroidd
为什么你不能做到那个? - Maciej Ciemięga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接