【安卓笔记】RecyclerView+SwipeRefreshLayout示例

通过这篇文章你将学会:
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);
    }
}






郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。