首页 > 移动平台 > 详细

Android RecycleView

时间:2015-07-15 10:41:55      阅读:259      评论:0      收藏:0      [点我收藏+]

Android RecyclerView 用来替代传统的ListView

 

要在Android Studio 中使用RecyclerView 首先要依赖相应的包

右键项目--->Open Module Settings---->Dependecies--->添加com.android.support:recycleview

package com.example.tanjin.learnrec;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
    private RecyclerView rv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rv = new RecyclerView(this);

        setContentView(rv);

        rv.setLayoutManager(new LinearLayoutManager(this));

        rv.setAdapter(new RecyclerView.Adapter() {

            class ViewHolder extends RecyclerView.ViewHolder
            {
                private TextView tv;
                public ViewHolder(View itemView)
                {
                    super(itemView);
                    tv = (TextView)itemView;
                }

                public TextView getTv()
                {
                    return  tv;
                }

            }

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                return new ViewHolder(new TextView(viewGroup.getContext()));

            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
                ViewHolder vh = (ViewHolder)viewHolder;
                vh.getTv().setText("item"+i);

            }

            @Override
            public int getItemCount() {
                return 1000;
            }
        });



    }



}

效果:

技术分享

可以上下滑动

接下来,用一个数组来实现RecycleView

增加一个字符串数组

private String[] data = new String[]{"Hello","Android"};

更改onBindViewHolder方法和getItemCount方法

public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
 ViewHolder vh = (ViewHolder)viewHolder;
 vh.getTv().setText(data[i]);
}
 public int getItemCount() {
       return data.length;
        }

再次运行

技术分享

由以上可知,使用RecyclerView的重点在设置Adapter

onCreateViewHolder 即创建ViewHolder

onBindViewHolder 即绑定ViewHolder,设置ViewHolder里面的View

getItemCount 返回列表一共有多少项

 

Android RecycleView

原文:http://www.cnblogs.com/six-moon/p/4647470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!