使用
- recyclerview基于v7包,需要現(xiàn)在項(xiàng)目中引入v7或單獨(dú)引入recyclerview.
- 去除滑動(dòng)到邊緣自帶的陰影效果
<android.support.v7.widget.RecyclerView
...
android:overScrollMode="never"/>
3.recyclerview無(wú)自帶點(diǎn)和觸摸事件,需要自行編寫接口進(jìn)行監(jiān)聽(tīng),示例代碼:
//不限于OnClickListener ,OnLongClickListener, OnTouchListener等等,任意接口
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
implements View.OnClickListener {
...
//實(shí)例化接口
private OnItemClickListener onItemClickListener;
@Override
public void onClick(View v) {
//加入自定義的接口方法
if (onItemClickListener!=null){
onItemClickListener.onItemClick((Integer) v.getTag());
}
}
//自定義接口
public interface OnItemClickListener{
void onItemClick(int position);
}
//在activity內(nèi)設(shè)置監(jiān)聽(tīng)
public void setOnItemClickListener(OnItemClickListener itemClickListener) {
onItemClickListener = itemClickListener;
}
//給每個(gè)item設(shè)置tag
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
...
viewHolder.itemView.setTag(position);
...
}
//給每個(gè)item視圖設(shè)置事件監(jiān)聽(tīng)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View inflate;
inflate =...;
inflate.setOnClickListener(this);
...
}
...
}
- 設(shè)置添加刪除動(dòng)畫,默認(rèn)動(dòng)畫添加刪除為淡入淡出.繼承SimpleItemAnimator重寫方法可自定義動(dòng)畫.
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
5.通過(guò)設(shè)置不同的LayoutManager啟用不同的布局
/*
* 1. LinerLayoutManager 以垂直或者水平列表方式展示Item
* 2. GridLayoutManager 以網(wǎng)格方式展示Item
* 3. StaggeredGridLayoutManager 以瀑布流方式展示Item
*/
mRecyclerView.setLayoutManager(mLayoutManager);
踩坑
- Recyclerview高度根據(jù)內(nèi)部item數(shù)目進(jìn)行隨動(dòng)時(shí),即高度設(shè)置為wrap_content,當(dāng)綁定的adapter數(shù)據(jù)源size由1變?yōu)?時(shí),notifyDataSetChanged()后最后一條數(shù)據(jù)仍在顯示,add一條數(shù)據(jù)后再次notifyDataSetChanged(),數(shù)據(jù)會(huì)替換為新增的數(shù)據(jù).
解決:高度設(shè)置為任意固定值可解決. - 由于組件重用導(dǎo)致數(shù)據(jù)混亂傻瓜解決方法
adapter內(nèi)viewholder設(shè)置setIsRecyclable為false,即不重用組件,在item數(shù)目少時(shí)可有效解決.
mHolder.setIsRecyclable(false);
持續(xù)更新