Android学习笔记——Recycler使用详解之基础篇

今天来详细的学习RecyclerView的知识,从基础到详细的完全学会使用RecyclerView,首先是基础部分。

使用步骤:

1.在gradle文件中添加依赖

compile 'com.android.support:recyclerview-v7:23.1.1'

注:这里版本需要与appcompat一致

2.在xml文件中使用RecyclerView



3.在Activity或Fragment中使用

private RecyclerView recyclerView;
recyclerView  = (RecyclerView) findViewById(R.id.recycler_view);
//设置布局方式
//线性类似ListView
recyclerView.setLayoutmanager(new LinearLayoutManager(this));
//线性宫各类似GridView,3是列数
//recyclerView.setLayoutmanager(new GridLayoutManager(this,3));
//瀑布流形式
//recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, OrientationHelper.VERTICAL));
recyclerView.setAdapter(adpter);

** 4.编写适配器Adapter类**

public class Fragment4Adapter extends RecyclerView.Adapter {

    private final LayoutInflater inflater;
    private final Context context;
    private List Titles;

    public Fragment4Adapter(Context context, List titles) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.Titles = titles;
    }

    @Override
    public Fragment4Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //找到item的布局
        View view= LayoutInflater.from(context).inflate(R.layout.list_items3,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(Fragment4Adapter.MyViewHolder holder, int position) {
        holder.textView.setText(Titles.get(position));
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        public MyViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView.findViewById(R.id.textView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e("TAG","你点击了"+getPosition()+"行");
                    Toast.makeText(context,"你点击了"+getPosition()+"行",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

至此,我们就完成了RecyclerView的基本实现。

你可能感兴趣的:(Android学习笔记——Recycler使用详解之基础篇)