安卓学习笔记------RecyclerView的基本用法

今天复习了一遍RecyclerView的基本用法,好长时间没有自己写过,加上之前用的也少,发现基本上都快忘了,看来以后还要多练。
首先在Gradle添加依赖

compile 'com.android.support:recyclerview-v7:21.0.+'

创建布局文件


    

    

Activity,通过LayoutManager可以设置不同的布局

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ArrayList mData;
    private HomeAdapter mAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        mAdapter=new HomeAdapter(initData());
        //创建默认的线性LayoutManager
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //创建GridView网格布局管理器
//        recyclerView.setLayoutManager(new GridLayoutManager(this,5));
        //创建瀑布就式布局管理器
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
                StaggeredGridLayoutManager.VERTICAL));
        recyclerView.setAdapter(mAdapter);
    }

    private ArrayList initData() {
        mData = new ArrayList<>();
        for (int i = 'A'; i < 'Z'; i++) {
            mData.add((char) i + "");
        }
        return mData;
    }
}

item布局


    


Adapter

class HomeAdapter extends RecyclerView.Adapter {
    ArrayList mData;

    public HomeAdapter(ArrayList list) {
        this.mData = list;
    }

    //创建新的view,被LayoutManager调用
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }
    //将数据与界面进行绑定
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv.setText(mData.get(position));
    }


    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    /**
     * 自定义的ViewHolder,持有每个Item布局界面的所有元素
     * */
    class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView tv;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv= (TextView) itemView.findViewById(R.id.num);
        }
    }

}

你可能感兴趣的:(安卓学习笔记------RecyclerView的基本用法)