RecyclerView:添加项目装饰的页脚?

时间:2016-08-15 06:47:50

标签: android android-recyclerview

是否可以使用项目装饰添加页脚,而不使用适配器?由于我正在处理一个非常复杂的适配器,它有很多不同的视图类型,我想在我的应用程序的每个列表中无缝添加一个相同的页脚。

1 个答案:

答案 0 :(得分:0)

据我所知,这不是最好的做法。

这是来自RecyclerView.ItemDecoration类的描述:

 /**
 * An ItemDecoration allows the application to add a special drawing and layout offset
 * to specific item views from the adapter's data set. This can be useful for drawing dividers
 * between items, highlights, visual grouping boundaries and more.

但是,根据适配器viewtype divider必须处理的实现自己的分隔符时,可以设置特定的行为。这是我在一个在线课程中使用的示例代码:

public class Divider extends RecyclerView.ItemDecoration {

private Drawable mDivider;
private int mOrientation;

public Divider(Context context, int orientation) {
    mDivider = ContextCompat.getDrawable(context, R.drawable.divider);
    if (orientation != LinearLayoutManager.VERTICAL) {
        throw new IllegalArgumentException("This Item Decoration can be used only with a RecyclerView that uses a LinearLayoutManager with vertical orientation");
    }
    mOrientation = orientation;
}

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == LinearLayoutManager.VERTICAL) {
        drawHorizontalDivider(c, parent, state);
    }
}

private void drawHorizontalDivider(Canvas c, RecyclerView parent, RecyclerView.State state) {
    int left, top, right, bottom;
    left = parent.getPaddingLeft();
    right = parent.getWidth() - parent.getPaddingRight();
    int count = parent.getChildCount();
    for (int i = 0; i < count; i++) {
    //here we check the itemViewType we deal with, you can implement your own behaviour for Footer type.
    // In this example i draw a drawable below every item that IS NOT Footer, as i defined Footer as a button in view
        if (Adapter.FOOTER != parent.getAdapter().getItemViewType(i)) {
            View current = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) current.getLayoutParams();
            top = current.getTop() - params.topMargin;
            bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == LinearLayoutManager.VERTICAL) {
        outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    }
}

或者您可以使用名为Flexible Divider的库,允许使用自定义drawable或资源。