RecyclerView具有动态大小的元素

时间:2015-01-25 20:14:13

标签: java android material-design android-recyclerview

我正在尝试从listview切换到recyclerview,但似乎无法弄清楚如何最好地回收视图。我想要的是在cardview中的一组cardviews。数据集类似于不同类别的一群学生。每个班级都有不同的规模,他们将在同一张卡片中出现。

目前我所拥有的是以下xml,其中'tv1'将包含该类的标题,学生名称将动态添加到'card_ll'中。我遇到的问题是我手动为每个学生姓名扩充视图,并根据班级中有多少学生添加/清除线性布局。请注意,学生人数不为零,但无法事先确定。

有没有办法重复使用每张学生证的观点?

由于

的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view1"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="2dp">

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

        <TextView
            android:id="@+id/tv1"
            android:textColor="#000000"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.CardView
            xmlns:card_view="http://schemas.android.com/apk/res-auto"
            android:id="@+id/card_view2"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            card_view:cardCornerRadius="2dp">
            <LinearLayout
                android:id="@+id/card_ll"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="vertical" >

            </LinearLayout>

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

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

适配器onBindViewHolder实现

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
     final ClassType ec = mDataset.get(position);
    final String name = ec.classtitle;

    holder.tv1.setText(ec.header1);

    if( ec.studentlist!=null && ec.studentlist.size()>0) {
        holder.cardll.removeAllViews();
        for (Student s:        ec.studentlist) {
            TextView tv = new TextView(mContext);
            tv.setText( s.getName());
            tv.setTextColor(Color.BLACK);
            holder.cardll.addView(tv);
        }
    }
}

0 个答案:

没有答案