使用RecycleView做网格布局

使用RecycleView代替GridView做网格布局,但recycleview没有提供item的点击事件,后在adapter中做了一个点击事件,recycleview要比listview和gridview更加灵活,性能上更加优化。

下面是在activity中的代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view=inflater.inflate(R.layout.fragment_find, container, false);
    recyclerView= (RecyclerView) view.findViewById(R.id.fm_find_recycle);
    List<FindBean> list=new ArrayList<>();	//这个bean对象自己建
    list.add(new FindBean(R.drawable.head_zhibo,"直播"));
    list.add(new FindBean(R.drawable.head_tieba,"贴吧"));

    FindAdapter adapter=new FindAdapter(list,getActivity());
    recyclerView.setAdapter(adapter);		//和gridview一样直接setAdapter
    recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3)); //这里是设置为网格布局,后边3的参数是列数

    return view;
}

下面是adapter的代码:

public class FindAdapter extends RecyclerView.Adapter{
    private List<FindBean> list;
    private Context context;

    public FindAdapter(List<FindBean> list, Context activity) {
        this.list=list;
        this.context=activity;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {			//这里直接return一个holder对象,参数为item的view
        return new HalderViewHolder(LayoutInflater.from(context).inflate(R.layout.find_item,null));
    }

    @Override		
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {			//在这部分做对UI的操作
        ((HalderViewHolder)holder).iv.setImageResource(list.get(position).getHead());
        ((HalderViewHolder)holder).tv.setText(list.get(position).getName());				//由于RecycleView没有提供对item的点击事件,暂时是
        ((HalderViewHolder)holder).item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, ZhiBoActivity.class));
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    class HalderViewHolder extends RecyclerView.ViewHolder{	//holder是继承RecycleView的用法基本与gridview相同
        @ViewInject(R.id.find_item_iv)
        private ImageView iv;
        @ViewInject(R.id.find_item_tv)
        private TextView tv;
        @ViewInject(R.id.find_item_item)
        private LinearLayout item;

        public HalderViewHolder(View itemView) {
            super(itemView);
            ViewUtils.inject(this,itemView);
        }

    }
}


下面是XML里的代码:

    android:id="@+id/fm_find_recycle"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"/>

这样就OK了,这个只是一个初级的demo,recycleview还有很多可以实现的很多布局,基本可以替代list和grid,非常好用。





你可能感兴趣的:(安卓学习)