相信现在大家对RecyclerView都不陌生了,相比ListView,RecyclerView在最新的support-V7版本中提供支持,ListView、GirdView还有瀑布流式布局,避免在绑定的时候重复创建数据,从而提高性能.
下面来看下效果:
RecyclerView基本用法:
xml中引用:
Activity中使用:
adapter中代码:
packagecom.example.testrecycleveiw;
importandroid.content.Context;
importandroid.graphics.Color;
importandroid.support.v7.widget.RecyclerView;
importandroid.util.Log;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.TextView;
importjava.util.ArrayList;
/**
* author:wanjianhua on 2017/2/28 16:01
* email:1243381493@qq.com
*/
public classRecyclerAdapterextendsRecyclerView.Adapter {
privateArrayListitemtext;
privateArrayListheight=newArrayList<>();
privateContextcontext;
RecyclerAdapter(Context context,ArrayList itemtext) {
this.itemtext= itemtext;
this.context= context;
notifyDataSetChanged();
}
@Override
publicMyHorderViewonCreateViewHolder(ViewGroup parent, intviewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, null);
MyHorderView holder =newMyHorderView(view);
holder.itemcontent= (TextView) view.findViewById(R.id.text_content);
// holder.itemcontent.setHeight(Math.round(10) * 20);
returnholder;
}
@Override
public voidonBindViewHolder(MyHorderView holder, intposition) {
inttemp = (int) (50* Math.random() +200);
height.add(temp);
holder.itemcontent.setText(itemtext.get(position));
holder.itemcontent.getLayoutParams().height=height.get(position);
holder.itemcontent.setBackgroundColor(Color.rgb((int) (Math.random() *255),(int) (Math.random() *255),(int) (Math.random() *255)));
}
@Override
public intgetItemCount() {
returnitemtext.size();
}
classMyHorderViewextendsRecyclerView.ViewHolder {
privateTextViewitemcontent;
publicMyHorderView(View itemView) {
super(itemView);
}
}
}
与AdapterView使用的适配器不同,默认的实现中RecyclerView没有实现onItemClickListener和onItemLongClickListener事件,在实际的开发中需要我们自己去实现,可以通过回调或者监听onTouch,一般选择回调方式。最后一点不同的是更新RecyclerView时,从适配器上添加或移除条目时增加了notifyItemInserted(position)和notifyItemRemoved(position)可明确通知适配器,而不是简单调用notifyDataSetChanged(),当然也可以直接notifyDataSetChanged()。