刷新和加载
//刷新
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
page = 1;
getData();
adapter.updateData(data);
srl.setRefreshing(false);
}
});
//加载更多
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//managerrecycler的布局管理器
int lastVisibleItemPosition = manager.findLastVisibleItemPosition();
if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItemPosition == adapter.getItemCount() - 1) {
Log.d("MainActivity===", "=============最后一条");
page++;
getData();
adapter.addData(data);
}
}
});
自定义点击事件
//自定义接口类
public interface OnClickRecyclerListner {
void onItemClick(View view,int position);
void onLongItemClick(View view,int position);
}
//adapter点击事件;
private OnClickRecyclerListner listner;
//设置点击事件;
public void setLisner(OnClickRecyclerListner lisner){
this.listner=lisner;
}
//返回对应的viewholder
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.item, null);
final MyViewHolder holder=new MyViewHolder(view);
//判断是否设置了点击事件;
if(listner!=null){
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//holder.getLayoutPosition()获取点击的条目位置;
listner.onItemClick(view,holder.getLayoutPosition());
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
listner.onLongItemClick(view,holder.getLayoutPosition());
//防止与click事件冲突
return true;
}
});
}
return holder;
}
//MainActivity调用
adapter.setLisner(new OnClickRecyclerListner() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this,position+"",Toast.LENGTH_LONG).show();
}
@Override
public void onLongItemClick(View view, int position) {
Toast.makeText(MainActivity.this,position+" 长摁",Toast.LENGTH_SHORT).show();
}
});