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

2017-12-07  本文已影响0人  Jotyy

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

使用步骤:

1.在gradle文件中添加依赖

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

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

2.在xml文件中使用RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recycler_view"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

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<Fragment4Adapter.MyViewHolder> {

    private final LayoutInflater inflater;
    private final Context context;
    private List<String> Titles;

    public Fragment4Adapter(Context context, List<String> 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的基本实现。

上一篇下一篇

猜你喜欢

热点阅读