2016-08-15 66 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