安卓v7支持包下的ListView替代品————RecyclerView

RecyclerView這個控件也出來好久了,相信你們也學習的差很少了,若是還沒學習的,或許我能夠帶領你們體驗一把這個藝術般的控件。java

 

項目已經同步至github:https://github.com/nanchen2251/recyclerViewDemoandroid

據官方介紹,該控件是屬於之間用的很是多的ListView和GridView的替代品,既然能替代用的如此廣泛的它們,這天然有其該有的優點。git

1)相對於ListView而言RecyclerView的優點體如今:github

①封裝了以前ListView的優化,封裝了以前ViewHolder的複用,這樣在自定義適配器的時候咱們面向的再也不是View,而是一個ViewHolder.app

②提供了插板式的體驗,高度解耦,異常靈活,針對每一項的顯示抽取出了相應的類來控制每個item的顯示。若想實現網格視圖或者瀑布流或者橫向的ListView均可以經過制定不同的LayoutManager來實現高大上的效果,這樣就能夠針對本身的業務邏輯隨意發揮了。ide

③如今的RecyclerView對增刪也有了動畫的加入,而且你還能夠自定義這些動畫。佈局

④對於Adaper適配器,如今刷新也增長了相應的方法,雖然以前的notifyDataSetChanged()一樣能夠實現這樣的效果,可是每次刷新整個界面在數據多的時候必然會大大影響用戶體驗。因此Adapter增長了更新數據的方法notifyItemInserted和notifyItemRemoved,這樣就能夠在增刪數據的時候只刷新被操做的Item,並且還加入了高大上的動畫效果呢。學習

2)基本用法:優化

相信描述了這麼多,你必定對這個神奇的控件火燒眉毛想嘗試一波了。要用到這個RecyclerView很簡單,首先在Gradle中添加支持包:動畫

compile 'com.android.support:recyclerview-v7:24.0.0'

下面就先來一個簡單的用法,首先來Activity

package com.example.nanchen.recyclerviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements MyAdapter.OnRecyclerItemClickListener {

    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
//            list.add(String.format(Locale.CHINA, "第%03d條數據%s", i, i % 2 == 0 ? "" : "-----------------------"));
            list.add(String.format(Locale.CHINA, "第%03d條數據", i));
        }
        adapter = new MyAdapter(this, list);
        adapter.setOnRecyclerItemClickListener(this);
        recyclerView.setAdapter(adapter);

        DefaultItemAnimator animator = new DefaultItemAnimator();
        animator.setRemoveDuration(1000);
        recyclerView.setItemAnimator(animator);
        //recyclerView.addItemDecoration(new MyDividerItemDecoration(this,MyDividerItemDecoration.VERTICAL_LIST));

        //最後一個參數是反轉佈局必定是false,爲true的時候爲逆向顯示,在聊天記錄中可能會有使用
        //這個東西在顯示後纔會加載,不會像ScollView同樣一次性加載致使內存溢出
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);

        //        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        //        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        //            @Override
        //            public int getSpanSize(int position) {
        //                if (position == 0){
        //                    return 3;
        //                }
        //                return 1;
        //            }
        //        });
        //        recyclerView.setLayoutManager(gridLayoutManager);

//        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    @Override
    public void OnRecyclerItemClick(RecyclerView parent, View view, int position, String data) {
        Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
        adapter.remove(position);
    }
}

  在上面的Activity代碼中,可見,咱們須要本身指定LayoutManager,代碼中用的是LinearLayoutMagener,你能夠試試其餘的。

再看看Adapter,有一個對大多數人來講很悲催的是,咱們的ListView中必定會有的點擊事件,而RecyclerView並無提供這樣的方法,這些點擊事件都是須要咱們本身學的,我這裏Adapter就簡單的實現了下,點擊就會刪除該Item。

package com.example.nanchen.recyclerviewdemo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * 自定義RecyclerView的Adapter
 * Created by 南塵 on 16-7-15.
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener {

    private Context context;
    private List<String> list;
    private OnRecyclerItemClickListener listener;
    private RecyclerView recyclerView;

    public void setOnRecyclerItemClickListener(OnRecyclerItemClickListener listener) {
        this.listener = listener;
    }

    public MyAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

    //在爲RecyclerView提供數據的時候調用
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView = recyclerView;
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recyclerView = null;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.text.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onClick(View v) {
        if (recyclerView != null && listener != null){
            int position = recyclerView.getChildAdapterPosition(v);
            listener.OnRecyclerItemClick(recyclerView,v,position,list.get(position));
        }
    }

    /**
     * 刪除指定數據
     * @param position 數據位置
     */
    public void remove(int position){
        list.remove(position);
//        notifyDataSetChanged();
        notifyItemRemoved(position);//這樣就只會刪除這一條數據,而不會一直刷

    }

    /**
     * 插入數據
     * @param position 插入位置
     * @param data 插入的數據
     */
    public void insert(int position,String data){
        list.add(position,data);
        notifyItemInserted(position);

    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        private final TextView text;

        public ViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.item_text);
        }
    }


    /**
     * 自定義RecyclerView的點擊事件
     */
    interface OnRecyclerItemClickListener{
        void OnRecyclerItemClick(RecyclerView parent,View view,int position,String data);
    }

}

  繼承這個Adapter須要指定一個ViewHolder的泛型,固然這個ViewHolder一般是由咱們做爲一個靜態類本身寫的。其餘這個就像咱們以前ListView中的BaseAdapter同樣。

本身還能夠實現其餘的點擊事件。

下面看下Xml,第一個是主佈局,第二個是每個項的佈局,我這裏就簡單隻實現一個TextView了。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nanchen.recyclerviewdemo.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_recycler"/>

</RelativeLayout>

  

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">

    <TextView
        android:id="@+id/item_text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

  這樣運行出來你估計就會看到沒有分割線,那麼分割線怎麼弄呢,看下文檔,須要咱們本身去寫,這個網上有不少。

上一個我看到過不少次的。

package com.example.nanchen.recyclerviewdemo;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by 南塵 on 16-7-15.
 */
public class MyDividerItemDecoration 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 MyDividerItemDecoration(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, RecyclerView.State state) {
        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);
            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, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        }else{
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}

  這樣使用的是系統的分割線。

這樣在Style中能夠本身更改。

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        
        <item name="android:listDivider">@drawable/divider_bg</item>
    </style>


</resources>

  自定義一個Drawble

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >

    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />
    <size android:height="4dp"/>

</shape>

  別忘了去把以前我給的MainActivity.java中把分割線那句代碼解去註釋。

        //增長分割線
        recyclerView.addItemDecoration(new MyDividerItemDecoration(this,MyDividerItemDecoration.VERTICAL_LIST));

最後上一波簡單的運行圖吧。

 

 好了,我也說的不是不少,你們能夠經過更多搜索出你想要的!

相關文章
相關標籤/搜索