Android RecycleView

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;

            }

        });







    }







}

效果:

Android RecycleView

可以上下滑动

接下来,用一个数组来实现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;

        }

再次运行

Android RecycleView

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

onCreateViewHolder 即创建ViewHolder

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

getItemCount 返回列表一共有多少项

 

你可能感兴趣的:(android)