Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android5.0控件-RecyclerView

Android5.0控件-RecyclerView

編輯:關於Android編程

Android 5.0引入了一個全新的列表控件-RecyclerView,這個控件更為靈活,同時也擁有比ListView和GridView控件較多的優點:例如Item View的創建、View的回收以及重用等機制。

RecyclerView控件提供了以下兩種方法來進行簡化和處理大數量集合:

 采用LayoutManager來處理Item的布局

 提供Item操作的默認動畫,例如在增加或者刪除item的時候

可以自定義LayoutManager或者設置添加/刪除的動畫,整體的RecyclerView結構圖如下:

這裡寫圖片描述

為了使用RecyclerView控件,需要創建一個Adapter和一個LayoutManager類,Adapter:繼承自RecyclerView.Adapetr類,主要用來將數據和布局item進行綁定。LayoutManager:布局管理器,設置每一項view在RecyclerView中的位置布局以及控件item view的顯示或者隱藏.當View重用或者回收的時候,LayoutManger都會向Adapter來請求新的數據來進行替換原來數據的內容。這種回收重用的機制可以提供性能,避免創建很多的view或者是頻繁的調用findViewById方法。這種機制和ListView還是很相似的。<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPlJlY3ljbGVyVmlld8zhuanBy8j91tbE2tbDtcRMYXlvdXRNYW5hZ2VyOjwvcD4NCjxwPiZuYnNwO0xpbmVhckxheW91dE1hbmFnZXI6z9/Q1LK8vtYsuuHP8rvy1d/X3c/yu6y2r8HQse08L3A+DQo8cD4mbmJzcDtHcmlkTGF5b3V0TWFuYWdlcjqx7bjxsry+1jwvcD4NCjxwPiZuYnNwO1N0YWdnZXJlZEdyaWRMYXlvdXRNYW5hZ2VyOsH3yr2yvL7WLMD9yOfG2bK8wffQp7n7PC9wPg0KPHA+tbHIu7P9wcvJz8PmtcTI/dbWxNqyv7K8vtbWrs3io6zO0sPHu7m/ydLUvMyz0FJlY3ljbGVyVmlldy5MYXlvdXRNYW5hZ2VywLTKtc/W0ru49tfUtqjS5bXETGF5b3V0TWFuYWdlcqGjPC9wPg0KPHA+UmVjeWNsZXJWaWV3ttTT2kl0ZW21xMztvNO6zcm+s/3Kx8SsyM+/qsb0tq+7rbXEoaPO0sPHtbHIu9Kyv8nS1M2ouf1SZWN5Y2xlclZpZXcuSXRlbUFuaW1hdG9ywOC2qNbGtq+7raOsyLu6882ouf1SZWN5Y2xlclZpZXcuc2V0SXRlbUFuaW1hdG9yKCm3vbeowLS9+NDQyrnTw6GjPC9wPg0KPHA+UmVjeWNsZXJWaWV3s6PTw8DgOjwvcD4NCjxwPjxpbWcgYWx0PQ=="這裡寫圖片描述" src="/uploadfile/Collfiles/20160612/2016061213383598.png" title="\" />
下面通過一個簡單實例對RecyclerView有一個簡單的理解。

主布局文件代碼(activity_main.xml):



    

注意要引入V7的包才能使用RecyclerView控件,如下圖:

這裡寫圖片描述

子布局文件代碼(item.xml):



    

適配器類代碼(MyAdapter.java):

public class MyAdapter extends RecyclerView.Adapter {
    private Context context;
    private List datas;
    public  MyAdapter(Context context,List datas){
        this.context=context;
        this.datas=datas;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                context).inflate(R.layout.item, parent,
                false));
        return holder;
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv.setText(datas.get(position));
    }
    @Override
    public int getItemCount() {
        return datas.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
        public MyViewHolder(View view) {
            super(view);
            tv = (TextView) view.findViewById(R.id.id_num);
        }
    }

適配器類繼承自RecyclerView.Adapter,這裡有幾個方法需要解釋一下其用法:
 構造方法- MyAdapter,傳入了Context對象和數據集合,這點和ListView一樣。
 OnCreateViewHolder方法,這是必須要覆寫的方法,返回一個ViewHolder對象。
 onBindViewHolder方法:綁定控件數據。
 getItemCount方法:返回數據項個數。
MainActivity代碼(MainActivity.java):

public class MainActivity extends Activity {
    private RecyclerView mRecyclerView;
    private List mDatas;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(myAdapter = new MyAdapter(this,mDatas));
    }
    protected void initData() {
        mDatas = new ArrayList();
        for (int i = 1; i < 20; i++) {
            mDatas.add("" +  i);
        }
    }
}

initData方法初始化了19條數據,setLayoutManger方法設置RecyclerView的排版方式,一般有三種:
 LinearLayoutManager 線行管理器,支持橫向、縱向,類似ListView。
 GridLayoutManager 網格布局管理器,類似GridView。
 StaggeredGridLayoutManager 瀑布流式布局。
運行項目實例如下:
這裡寫圖片描述
我們可以看到,默認是不顯示item之間的分割線的,添加分割線的方法比較固定,下面講解一下如何實現。
這裡需要一個DividerItemDecoration類:

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
    private Drawable mDivider;
    private int mOrientation;
    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }
    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }
    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }
    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(
                    parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

這個方法比較固定,大家可以網上自行下載。在MainActivity中添加一條語句即可添加橫線:

public class MainActivity extends Activity {
    private RecyclerView mRecyclerView;
    private List mDatas;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(myAdapter = new MyAdapter(this,mDatas));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

    }
    protected void initData() {
        mDatas = new ArrayList();
        for (int i = 1; i < 20; i++) {
            mDatas.add("" +  i);
        }
    }
}

調用了RecyclerView的addItemDecoration方法,傳入DividerItemDecoration對象,實例化該對象時傳入了兩個參數,一個是上下文對象,一個是排列布局方式。
運行項目實例如下:
這裡寫圖片描述
這時可以看到每個Item之間有了一條淺淺灰色分割線。這個灰色的分割線不夠明顯,也不美觀,我們可以借助主題的listDivider屬性改變分割線,找到當前主題,添加一條語句如下(加粗語句):


    
**

再次運行項目實例如下:
這裡寫圖片描述
分割線變成了我們自定義個bg圖片,這時就可以實現任意的自定義了。
上面實現了類似ListView的布局方式,下面實現一個類似GridView的布局方式,這裡需要修改一下MainActivity的一條語句(加粗),如下:

public class MainActivity extends Activity {
    private RecyclerView mRecyclerView;
    private List mDatas;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this,4));
        mRecyclerView.setAdapter(myAdapter = new MyAdapter(this, mDatas));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

    }
    protected void initData() {
        mDatas = new ArrayList();
        for (int i = 1; i < 20; i++) {
            mDatas.add("" +  i);
        }
    }
}

setLayoutManager方法傳入了GridLayoutManager的對象,實例化該對象需要兩個參數,第一個是上下文對象,第二個是每一行顯示item的個數。
運行實例如下:
這裡寫圖片描述

可以看到類似GridView的效果,但是分割線好像不太正確,我們還需要新建一個分割線類:

public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
    private Drawable mDivider;
    public DividerGridItemDecoration(Context context) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }
    @Override
    public void onDraw(Canvas c, RecyclerView parent, State state) {
        drawHorizontal(c, parent);
        drawVertical(c, parent);
    }
    private int getSpanCount(RecyclerView parent) {
        // 列數
        int spanCount = -1;
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager)
                    .getSpanCount();
        }
        return spanCount;
    }
    public void drawHorizontal(Canvas c, RecyclerView parent) {
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getLeft() - params.leftMargin;
            final int right = child.getRight() + params.rightMargin
                    + mDivider.getIntrinsicWidth();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
    public void drawVertical(Canvas c, RecyclerView parent) {
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getTop() - params.topMargin;
            final int bottom = child.getBottom() + params.bottomMargin;
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicWidth();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
    private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
                                int childCount) {
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            if ((pos + 1) % spanCount == 0)// 如果是最後一列,則不需要繪制右邊
            {
                return true;
            }
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                if ((pos + 1) % spanCount == 0)// 如果是最後一列,則不需要繪制右邊
                {
                    return true;
                }
            } else {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最後一列,則不需要繪制右邊
                    return true;
            }
        }
        return false;
    }
    private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
                              int childCount) {
        LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            childCount = childCount - childCount % spanCount;
            if (pos >= childCount)// 如果是最後一行,則不需要繪制底部
                return true;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            int orientation = ((StaggeredGridLayoutManager) layoutManager)
                    .getOrientation();
            // StaggeredGridLayoutManager 且縱向滾動
            if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                childCount = childCount - childCount % spanCount;
                // 如果是最後一行,則不需要繪制底部
                if (pos >= childCount)
                    return true;
            } else
            // StaggeredGridLayoutManager 且橫向滾動
            {
                // 如果是最後一行,則不需要繪制底部
                if ((pos + 1) % spanCount == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent) {
        int spanCount = getSpanCount(parent);
        int childCount = parent.getAdapter().getItemCount();
        if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最後一行,則不需要繪制底部
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最後一列,則不需要繪制右邊
        {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                    mDivider.getIntrinsicHeight());
        }
    }
}

getItemOffsets方法中進行了邏輯判斷,最後一行時,不必繪制底部分割線,最後一列,不必繪制右邊的分割線。將主題中的自定義分割線語句去除,再次運行項目:
這裡寫圖片描述
下面講解第三種布局方式-瀑布流的實現,首先我們修改MainActivity代碼如下:

public class MainActivity extends Activity {
    private RecyclerView mRecyclerView;
    private List mDatas;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
       // mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        mRecyclerView.setAdapter(myAdapter = new MyAdapter(this, mDatas));
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
     }
    protected void initData() {
        mDatas = new ArrayList();
        for (int i = 1; i < 100; i++) {
            mDatas.add("" +  i);
        }
    }
}

修改部分加粗,在setLayoutManager方法中傳入了StaggeredGridLayoutManager的對象,對象初始化傳入兩個參數,第一個是每一行的列數,第二個是布局方式。
此外,我們還需要修改適配器文件,隨機化子控件的高度,這樣才有瀑布流的效果,如下:

public class MyAdapter extends RecyclerView.Adapter {
    private Context context;
    private List datas;
    private List mHights;
    public  MyAdapter(Context context,List datas){
        this.context=context;
        this.datas=datas;
        mHights=new ArrayList<>();
        for (int i=0;i

新添加了一個List對象mHeights用於存儲隨機的高度數值,在onBindViewHolder方法中為TextView控件設置了隨機的高度。
運行實例如下:
這裡寫圖片描述
可以看出,所有的子Item的高度都是隨機產生的,也就產生了瀑布流的效果,我們可以看出,RecyclerView較傳統的控件來講使用更為靈活,在今後的開發中也將會經常用到。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved