使用GridLayout的Recyclerview。仅当下一个项目的日期不同时才添加分隔符

时间:2017-05-29 10:42:04

标签: android android-recyclerview grid-layout

我有RecyclerView GridLayout。我的数据是按日期排序的List个有序对象。如果下一个项目与当前项目具有不同的日期,我需要添加一个分隔符。这是我的班级:

public class ImageContentFragment extends Fragment  {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    recyclerView = (RecyclerView) mainView.findViewById(R.id.rc_recycler_view);
    adapter = new ContentAdapter(recyclerView.getContext());
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    int tilePadding = getResources().getDimensionPixelSize(R.dimen.tile_padding);
    recyclerView.setPadding(tilePadding, tilePadding, tilePadding, tilePadding);
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), sPrefs.getInt(GRID_COL_KEY, GRID_SPAN_COUNT)));
    return mainView;
}

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.MyViewHolder> {

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public ImageView picture;
        public TextView name;
        public boolean selected = false;
        public MyViewHolder(View view) {
            super(view);
            picture = (ImageView) itemView.findViewById(R.id.tile_picture);
            name = (TextView) itemView.findViewById(R.id.tile_title);
        }
    }

    public ContentAdapter(Context context) {
        mUlrPictures = getImageUrlForFolder(mediaStorageDir);
    }

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
        GridLayoutManager.LayoutParams lp = (GridLayoutManager.LayoutParams) v.getLayoutParams();
        lp.height = sPrefs.getInt(ICON_SIZE_KEY, ITEM_HEIGHT_MEDIUM);
        v.setLayoutParams(lp);
        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
            String imUrl = mUlrPictures.get(position % mUlrPictures.size()).getUrl();
            holder.name.setText(mUlrPictures.get(position % mUlrPictures.size()).getUrl());
            holder.selected = mUlrPictures.get(position % mUlrPictures.size()).getSelected();
        }
    }

    @Override
    public int getItemCount() {
        return mUlrPictures.size();
    }

}

}

最好的方法是什么?添加带有分隔符的TextView也很棒。

1 个答案:

答案 0 :(得分:0)

在item_image.xml文件中添加一个高度为2dp&amp;的视图width fill_parent,它作为分隔符,也分配id。

onBindViewHolder方法写一个逻辑来检查基于位置的日期,如果为true则使其显示分隔符视图,如果没有使分隔符View.gone

希望这会对你有所帮助