2016-08-15 11 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. 

は対処しなければなりません。

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と呼ばれるライブラリを使用することができます:ここで私は1つのオンラインコースで使用するサンプルコードを示します。

+0

あなたの答えのおかげでありがとうございます。アイテムデコレータが異なる目的を持っている可能性があるので、ベストプラクティスではないというのは正しいことです。おそらく、異なるビュータイプを持つ古いクリーナーアダプタに置き換えられる可能性があります。 – rqiu

関連する問題