文档章节

【学习笔记】RecyclerView的使用

小树coding
 小树coding
发布于 2015/06/26 10:08
字数 915
阅读 632
收藏 4

「深度学习福利」大神带你进阶工程师,立即查看>>>

为什么叫做RecyclerView?
  • 不关心Item是否显示在正确的位置,如何显示。(LayoutManager)
  • 不关心Item间如何分隔。(ItemDecoration)
  • 不关心Item增加与删除的动画效果。(ItemAnimator)
  • 仅仅关注如何回收与复用View。

RecylerView相关的重要类


  • Adapter
  • ViewHolder
  • LayoutManager
  • ItemDecoration
  • ItemAnimator

RecylerView能干什么?


  • Just like ListView
  • Just like GridView
  • 横向 ListView
  • 横向 GridView
  • 瀑布流
  • 定制Item增加与删除动画(ItemAnimator)
  • 需要手动为Adapter提供Item Click/longClick的回调

RecyclerView关于ListView的实现代码:

package cn.jiarong.myrecyclerview;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

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


public class MainActivity extends ActionBarActivity {

    private RecyclerView mRecyclerView;
    private List<String> mDatas;
    private MyAdapter adapter;

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

        initDatas();

        initViews();
        adapter = new MyAdapter(this, mDatas);
        mRecyclerView.setAdapter(adapter);

        //设置RecyclerView的布局管理
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //设置RecyclerView的item的分割线
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                //DividerItemDecoration.VERTICAL_LIST));

        adapter.setmOnItemClickListner(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int pos) {

                Toast.makeText(MainActivity.this, pos +" click:",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View v, int pos) {
                Toast.makeText(MainActivity.this, pos +" long click:",Toast.LENGTH_SHORT).show();
            }
        });
    }

    //加载视图
    private void initViews(){
        mRecyclerView = (RecyclerView)findViewById(R.id.mRecyclerView);
    }

    //初始化数据
    private void initDatas(){
        mDatas = new ArrayList<String>();
        for(int i='A';i<='z';i++){
            mDatas.add(""+(char)i);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        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
        switch (id){
            case R.id.action_add:
                adapter.addData(1, "insert a");
                break;
            case R.id.action_delete:
                adapter.deleteData(1);
                break;
            case R.id.action_listview:
                mRecyclerView.setLayoutManager(new LinearLayoutManager(this,
                        LinearLayoutManager.VERTICAL, false));

                break;
            case R.id.action_gridview:
                mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
                break;
            case R.id.action_hor_gridview:
                mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(5,
                        StaggeredGridLayoutManager.HORIZONTAL));
                break;
            case R.id.action_staggered:
                Intent intent = new Intent(this, StaggedActivity.class);
                startActivity(intent);
                break;
        }

        return super.onOptionsItemSelected(item);
    }
}



package cn.jiarong.myrecyclerview;

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

import java.util.List;

/**
 * Created by jiaronggeng on 15/6/25.
 */
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private LayoutInflater mInflater;
    private Context mContext;
    protected List<String> mDatas;

    public interface OnItemClickListener{
        public void onItemClick(View v, int pos);
        public void onItemLongClick(View v, int pos);
    }

    private OnItemClickListener mOnItemClickListner;

    public void setmOnItemClickListner(OnItemClickListener mOnItemClickListner) {
        this.mOnItemClickListner = mOnItemClickListner;
    }

    public void addData(int pos, String str){
        this.mDatas.add(pos, str);
        this.notifyItemInserted(1);
    }

    public void deleteData(int pos){
        this.mDatas.remove(pos);
        this.notifyItemRemoved(1);
    }

    public MyAdapter(Context context, List<String> datas){
        this.mContext = context;
        this.mDatas = datas;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder myViewHolder, final int i) {

        myViewHolder.m_tv.setText(mDatas.get(i));
        setUpEvent(myViewHolder);

    }

    protected void setUpEvent(final MyViewHolder myViewHolder){
        if (mOnItemClickListner != null) {
            myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int pos = myViewHolder.getLayoutPosition();
                    mOnItemClickListner.onItemClick(myViewHolder.itemView, pos);
                }

            });

            myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                    int pos = myViewHolder.getLayoutPosition();
                    mOnItemClickListner.onItemLongClick(myViewHolder.itemView, pos);

                    return false;
                }
            });
        }

    }

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

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = mInflater.inflate(R.layout.item, viewGroup, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }
}

class MyViewHolder extends ViewHolder{

    TextView m_tv;

    public MyViewHolder(View itemView) {
        super(itemView);
        m_tv = (TextView)itemView.findViewById(R.id.m_tv);

    }
}



瀑布流

package cn.jiarong.myrecyclerview;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

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


public class StaggedActivity extends Activity {

    private RecyclerView mRecyclerView;
    private List<String> mDatas;
    private StaggedAdapter adapter;

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

        initDatas();

        initViews();
        adapter = new StaggedAdapter(this, mDatas);
        mRecyclerView.setAdapter(adapter);

        //设置RecyclerView的布局管理
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.VERTICAL));

        adapter.setmOnItemClickListner(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int pos) {

            }

            @Override
            public void onItemLongClick(View v, int pos) {
                //长按删除
                adapter.deleteData(pos);
            }
        });

    }

    //加载视图
    private void initViews(){
        mRecyclerView = (RecyclerView)findViewById(R.id.mRecyclerView);
    }

    //初始化数据
    private void initDatas(){
        mDatas = new ArrayList<String>();
        for(int i='A';i<='z';i++){
            mDatas.add(""+(char)i);
        }
    }


}

package cn.jiarong.myrecyclerview;

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

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

/**
 * Created by jiaronggeng on 15/6/25.
 */
public class StaggedAdapter extends MyAdapter {

    private List<Integer> listHeight;

    public StaggedAdapter(Context context, List<String> datas){
        super(context, datas);

        listHeight = new ArrayList<Integer>();
        for(int i=0;i<mDatas.size();i++){
            listHeight.add((int)(100+Math.random()*300));
        }
    }

    @Override
    public void onBindViewHolder(MyViewHolder myViewHolder, int position) {

        ViewGroup.LayoutParams lp = myViewHolder.itemView.getLayoutParams();
        lp.height = listHeight.get(position);
        myViewHolder.itemView.setLayoutParams(lp);
        myViewHolder.m_tv.setText(mDatas.get(position));

        setUpEvent(myViewHolder);
    }


}






小树coding
粉丝 13
博文 120
码字总数 33884
作品 0
苏州
Android工程师
私信 提问
加载中
请先登录后再评论。
CDH5: 使用parcels配置lzo

一、Parcel 部署步骤 1 下载: 首先需要下载 Parcel。下载完成后,Parcel 将驻留在 Cloudera Manager 主机的本地目录中。 2 分配: Parcel 下载后,将分配到群集中的所有主机上并解压缩。 3 激...

cloud-coder
2014/07/01
6.8K
1
使用IBPP在C++中操作FireBird/Interbase数据库

FireBird是一种小巧的关系型数据库,它有多种版本,包括服务器版(象MySQL),单机版(象Access)以及嵌入式(象SQLite)。而且不管是服务器版还是嵌入式版它都完整支持视图、触发器、存储过程等...

Waiting4you
2009/07/26
3.8K
2
使用CImg处理三维图像

http://www.cppprog.com/2009/0429/110.html

Waiting4you
2009/05/05
1.6K
0
在C++中使用Lua

http://www.cppprog.com/2009/0209/62.html

Waiting4you
2009/05/05
1K
0
分享红薯推荐的数据库管理工具使用技巧

嘿嘿。。不好意思呀,打着红薯的旗号把你骗进来了。。 数据库管理工具 navicat 我们在查询大量数据的时候可能会想知道具体是哪儿出了毛病,影响 --- 性 ----能... 今天红薯介绍navicat给我。...

用户已屏蔽
2011/04/19
504
2

没有更多内容

加载失败,请刷新页面

加载更多

C#中const和readonly有什么区别? - What is the difference between const and readonly in C#?

问题: What is the difference between const and readonly in C#? C#中const和readonly什么区别? When would you use one over the other? 您什么时候可以使用另一个? 解决方案: 参考一...

fyin1314
18分钟前
17
0
百度地图SDK新版内测邀请

本文作者:用****9 百度地图开放平台为开发者提供七大基础服务能力,其中地图SDK和导航SDK是开发者广泛使用的重要基础服务,为了满足开发者更多使用需求以及提升开发者集成后的应用效果,本次...

百度开发者中心
前天
0
0
获取JavaScript数组中的所有唯一值(删除重复项) - Get all unique values in a JavaScript array (remove duplicates)

问题: I have an array of numbers that I need to make sure are unique. 我需要确定一个唯一的数字数组。 I found the code snippet below on the internet and it works great until th......

javail
今天
11
0
如何检查字符串是否为空? - How to check if the string is empty?

问题: Does Python have something like an empty string variable where you can do: Python是否有类似空字符串变量的内容可以在其中执行: if myString == string.empty: Regardless, wh......

富含淀粉
今天
19
0
您如何存储未跟踪的文件? - How do you stash an untracked file?

问题: I have changes to a file, plus a new file, and would like to use git stash to put them away while I switch to another task. 我对一个文件进行了更改,再加上一个新文件,并希......

技术盛宴
今天
39
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部