2016-08-15 67 views
2

是否有可能添加项目装饰页脚,而不使用适配器?由于我正在处理一个非常复杂的适配器,并且有很多不同的视图持有者类型,所以我希望为我的应用中的每个列表无缝添加一个相同的页脚。RecyclerView:添加项目装饰页脚?

+0

你使用的适配器与listView或gridview? –

+0

抱歉不清楚,但正如标题所述,我正在使用recyclerview – rqiu

回答

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分频器实现自己的除法时,您可以设置特定的行为必须处理。以下是我在一个在线课程使用的示例代码:

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库,允许使用自定义绘制或资源进行设置。

+0

感谢您的回答安东。你是不是最好的做法,因为项目装饰器可能有不同的用途,所以我可能会回退到旧的和干净的适配器,使用不同的视图类型。 – rqiu