如何制作高度可变的CardViews的网格布局?

时间:2015-07-11 08:08:28

标签: android android-layout material-design

我在XML中定义了多个CardView

<android.support.v7.widget.CardView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardPreventCornerOverlap="false"
    card_view:cardCornerRadius="4dp">
    <LinearLayout
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="@dimen/abc_text_size_title_material"
            android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</android.support.v7.widget.CardView>

对于手机,我已将多个CardView包裹在垂直LinearLayout中:

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

对于平板电脑,我想使用网格布局,类似于Material Design specs中使用的设计,请参见图片here

用于制作网格布局的最佳ViewGroup是什么?这些卡的高度可变,并且具有静态内容。

GridLayout无法使用,因为卡片的高度可变。

2 个答案:

答案 0 :(得分:12)

一段时间以来我遇到过同样的问题。是的,您不能使用GridLayout,因为您的卡片大小可变。那么你在寻找什么 StaggeredGridView ,它允许它的项目具有可变的大小。

您可以执行以下任一操作: -

1)您可以使用thisthis库。它们使用起来非常简单。我已经使用了两者,我可以向你保证他们完美地完成了他们的工作。

2)您可以尝试使用Google发送的RecyclerView.StaggeredGridLayoutManager

示例代码看起来像这样,

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
    recyclerView.setAdapter(adapter);

希望它对你有所帮助。

答案 1 :(得分:1)

对于平板电脑,您可以使用2个LinearLayouts。