相信現(xiàn)在大家對RecyclerView都不陌生了,相比ListView,RecyclerView在最新的support-V7版本中提供支持,ListView逸尖、GirdView還有瀑布流式布局,避免在綁定的時候重復(fù)創(chuàng)建數(shù)據(jù),從而提高性能.
下面來看下效果:
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使用的適配器不同,默認的實現(xiàn)中RecyclerView沒有實現(xiàn)onItemClickListener和onItemLongClickListener事件距误,在實際的開發(fā)中需要我們自己去實現(xiàn),可以通過回調(diào)或者監(jiān)聽onTouch害驹,一般選擇回調(diào)方式透绩。最后一點不同的是更新RecyclerView時芥挣,從適配器上添加或移除條目時增加了notifyItemInserted(position)和notifyItemRemoved(position)可明確通知適配器,而不是簡單調(diào)用notifyDataSetChanged()杖爽,當(dāng)然也可以直接notifyDataSetChanged()敲董。