【安卓筆記】RecyclerView+SwipeRefreshLayout示例

rowandjj發表於2015-03-29
通過這篇文章你將學會:
1.RecyclerView的基本用法;
2.SwipeRefreshLayout的基本用法;
3.為RecyclerView的item新增響應事件。

RecyclerView簡單說下,它是用來替代傳統ListView的,RecyclerView更加靈活,而且可以與動畫很好的結合,你可以很方便的為每個item增加各種動畫效果,另外,RecyclerView強制使用ViewHolder模式,可以提高效能。

截圖:


步驟:
1.新增依賴:
 compile 'com.android.support:recyclerview-v7:21.0.0'
 compile 'com.android.support:support-v4:22.0.0'
2.編寫activity佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="com.taobao.recyclerviewwithrefresh.ui.activity.GridActivity">
    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refreshLayout_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView_grid"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scrollbars="vertical"
            ></android.support.v7.widget.RecyclerView>
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
3.編寫每個item的佈局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="match_parent"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_height="50dp">
    <ImageView
        android:src="@mipmap/ic_launcher"
        android:padding="5dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        android:layout_height="match_parent"
        tools:text="ss"/>
</LinearLayout>
4.資料來源:
package com.taobao.recyclerviewwithrefresh.data;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Rowandjj on 2015/3/24.
 */
public class DataSource
{
    public static final List<String> generateData(int size)
    {
        if (size <= 0)
            return null;
        List<String> datas = new ArrayList<>();
        for (int i = 0; i < size; i++)
        {
            datas.add("這是列表資料"+i);
        }
        return datas;
    }
}
5.分隔條:
package com.taobao.recyclerviewwithrefresh.ui.adapter;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
 * Created by Rowandjj on 2015/3/24.
 */
public class MyItemDecoration extends RecyclerView.ItemDecoration
{
    private static final int[] ATTRS = {android.R.attr.listDivider};
    private Drawable mDivider;
    public MyItemDecoration(Context context)
    {
        TypedArray array = context.obtainStyledAttributes(ATTRS);
        // 獲取分隔條
        mDivider = array.getDrawable(0);
        array.recycle();
    }
    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state)
    {
        super.onDrawOver(c, parent, state);
        int count = parent.getChildCount();
        int left = parent.getPaddingLeft();
        int right = parent.getWidth()-parent.getPaddingRight();
        for(int i = 0; i < count; i++)
        {
            View v = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) v.getLayoutParams();
            int top = v.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left,top,right,bottom);
            mDivider.draw(c);
        }
    }
}
6.編寫資料介面卡,併為其增加點選響應事件
package com.taobao.recyclerviewwithrefresh.ui.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.taobao.recyclerviewwithrefresh.R;
import java.util.List;
/**
 * Created by Rowandjj on 2015/3/24.
 *
 */
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.ViewHolder>
{
    private List<String> datas = null;
    private OnItemClickListener mListener;
    public void setOnItemClickListener(OnItemClickListener listener)
    {
        this.mListener = listener;
    }
    public MainRecyclerAdapter(List<String> datas)
    {
        this.datas = datas;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
    {
        final View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        itemView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(mListener != null)
                {
                    mListener.OnItemClick(v, (String) itemView.getTag());
                }
            }
        });
        return new ViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position)
    {
        String s = datas.get(position);
        holder.bindData(s);
        holder.itemView.setTag(s);
    }
    @Override
    public int getItemCount()
    {
        return datas.size();
    }
    /**
     * 批量增加
     * */
    public void addItems(List<String> items)
    {
        if (items == null)
            return;
        this.datas.addAll(0, items);
        this.notifyItemRangeInserted(0, items.size());
    }
    public interface OnItemClickListener
    {
        public void OnItemClick(View view,String data);
    }
    static class ViewHolder extends RecyclerView.ViewHolder
    {
        private TextView mContent;
        public ViewHolder(View itemView)
        {
            super(itemView);
            mContent = (TextView) itemView.findViewById(R.id.tv);
        }
        public void bindData(String s)
        {
            if (s != null)
                mContent.setText(s);
        }
    }
}

RecyclerView沒有提供類似onItemClickListener之類的回撥,這裡我們自己實現了一個。。。

7.主頁面程式碼:
package com.taobao.recyclerviewwithrefresh.ui.activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.taobao.recyclerviewwithrefresh.R;
import com.taobao.recyclerviewwithrefresh.data.DataSource;
import com.taobao.recyclerviewwithrefresh.ui.adapter.MyItemDecoration;
import com.taobao.recyclerviewwithrefresh.ui.adapter.MainRecyclerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
 * 1.RecyclerView基本用法
 *      LayoutManager
 *      ItemAnimator
 *      ItemDecoration
 *
 *      RecyclerView.Adapter
 *      RecyclerView.ViewHolder
 *
 * 2.SwipeRefreshLayout用法
 *
 * 3.給RecyclerView的每個item新增響應事件的方式
 *
 * 4.控制RecyclerView滾動到某一具體位置: RecyclerView#scrollToPosition
 *
 *
 * */
public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener
{
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mRefreshlayout;
    private LinearLayoutManager mLinearLayoutManager;
    private MainRecyclerAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRefreshlayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        mRefreshlayout.setOnRefreshListener(this);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mAdapter = new MainRecyclerAdapter(DataSource.generateData(20));
        mRecyclerView.setAdapter(mAdapter);
        //每個item高度一致,可設定為true,提高效能
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        //分隔線
        mRecyclerView.addItemDecoration(new MyItemDecoration(this));
        //為每個item增加響應事件
        mAdapter.setOnItemClickListener(new MainRecyclerAdapter.OnItemClickListener()
        {
            @Override
            public void OnItemClick(View view, String data)
            {
                Toast.makeText(MainActivity.this, "data:" + data, Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    public void onRefresh()
    {
        new UpdateTask().execute();
    }
    private class UpdateTask extends AsyncTask<Void,Void,List<String>>
    {
        @Override
        protected List<String> doInBackground(Void... params)
        {
            try
            {
                Thread.sleep(2000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            List<String> strings = new ArrayList<>();
            strings.add("新資料1");
            strings.add("新資料2");
            strings.add("新資料3");
            strings.add("新資料4");
            return strings;
        }
        @Override
        protected void onPostExecute(List<String> strings)
        {
            mAdapter.addItems(strings);
           //通知重新整理完畢
            mRefreshlayout.setRefreshing(false);
           //滾動到列首部--->這是一個很方便的api,可以滑動到指定位置
            mRecyclerView.scrollToPosition(0);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_grid)
        {
            this.startActivity(new Intent(this, GridActivity.class));
            return true;
        }else if(id == R.id.action_settings)
        {
            Toast.makeText(MainActivity.this, "run...", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}






相關文章