RecyclerView与SwipeRefreshLayout结合可以实现下拉刷新。
布局文件:
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/id_swipe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/id_recyclerview_swipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
用SwipeRefreshLayout包裹RecyclerView,只能有一个子项.
代码:
String[] textList= {"123","456"};
swipeRefreshLayout.setOnRefreshListener(this);//设置监听
//设置进度条的颜色
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
android.R.color.holo_orange_light, android.R.color.holo_red_light);
//实例化适配器
myAdapter = new MyAdapter(textList);
//设置recyclerview的布局方式
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
//设置默认动画
recyclerView.setItemAnimator(new DefaultItemAnimator());
//绑定适配器
recyclerView.setAdapter(myAdapter);
适配器:
class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int OtherItemType = 1;
private static final int FinalItemType = 0;
private String[] list;
public MyAdapter(String[] list) {
this.list = list;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.simple_text_layout, null);
OtherViewHolder viewHolder = new OtherViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if(holder instanceof OtherViewHolder){
OtherViewHolder otherViewHolder = (OtherViewHolder) holder;
otherViewHolder.textView.setText(textList[position]);
}
}
@Override
public int getItemCount() {
return textList.length;
}
class OtherViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public OtherViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.id_simple_text);
}
}
}
重写onRefresh方法:
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
mHandler.sendEmptyMessageDelayed(1, 3000);
}
上述方法中,向handler发送延迟消息,延迟时间为3000ms,目的是为了显示刷新效果。
Handler:
private Handler mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
textList =new String[] {"A", "B", "C"};
myAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
};
};
这样就实现了RecyclerView的下拉刷新的功能。