在StaggeredGridLayoutManager和RecyclerView

时间:2018-02-08 17:25:42

标签: android android-recyclerview staggeredgridlayoutmanager

我正在尝试将时间表整合到我的应用中。起初我使用了普通的GridLayout,但我想连接学校科目。所以我切换到StaggeredGridLayoutManager来为项目设置不同的高度 。一切都有效,除了一件事。如果一个主题仅在一天中进行一个课程,则下一行中的第一个项目将被放置在间隙中。

这就是我的意思:
This is what I expected
How it looks

7号应该是星期一,而不是星期四。

这是我的ScheduleActivity调用我的自定义适配器

RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.schedule_recycler_view);
    recyclerView.setHasFixedSize(true);

    StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(7, StaggeredGridLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(staggeredGridLayoutManager);

    ScheduleAdapter rcAdapter = new ScheduleAdapter(subjects);
    recyclerView.setAdapter(rcAdapter);

这是我的适配器

public class ScheduleAdapter extends RecyclerView.Adapter<ScheduleAdapter.ViewHolder> {

private ArrayList<SubjectModel> items;

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
    public CardView cardView;
    public TextView content;

    public ViewHolder(View view) {
        super(view);
        cardView = (CardView) view.findViewById(R.id.schdule_card);
        content = (TextView) view.findViewById(R.id.schedule_content);
    }
}

// Provide a suitable constructor (depends on the kind of dataset)
public ScheduleAdapter(ArrayList<SubjectModel> items) {
    this.items = items;
}

// Create new views (invoked by the layout manager)
@Override
public ScheduleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.schedule_card, parent, false);
    return new ViewHolder(view);
}

public static float convertDpToPixel(float dp){
    DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
    float px = dp * (metrics.densityDpi / 160f);
    return Math.round(px);
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    final SubjectModel subject = items.get(position);
    int lessons = subject.getLessonCount();

    int i = lessons*2-2;
    int height = (int) (holder.itemView.getMinimumHeight()*lessons + convertDpToPixel(i));
    holder.cardView.setMinimumHeight(height);

    String text = subject.getSubjectName().substring(0, 2)+"\n"+subject.getSubjectRoom();
    holder.content.setText(text);
}

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
    return items.size();
}

}

讽刺的是,图片只是链接的。我是新来的,仍无权直接整合图片。

有谁知道如何解决问题? 我还没找到任何东西。

感谢您的帮助!

0 个答案:

没有答案