把想要实现下拉刷新的控件放在SwipeRefreshLayout中,就可以直接支持下拉刷新
<android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout>
虽然控件已经支持下拉刷新了,但是还要去处理具体逻辑
//下拉刷新 SwipeRefreshLayout mSwipeRefreshLayout; 找到SwipeRefreshLayout 布局 mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); 设置进度条的颜色 mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); 设置下拉刷新的监听事件。 mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshFruits(); } });
private void refreshFruits() { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(2000);让线程休眠两秒因为本地刷新太快,用户感觉不到 } catch (InterruptedException e) { e.printStackTrace(); } 在主线程中改变数据 runOnUiThread(new Runnable() { @Override public void run() { initFruits();//生成新的数据 adpapter.notifyDataSetChanged();//通知数据刷新 mSwipeRefreshLayout.setRefreshing(false);//刷新结束,并且隐藏刷新进度条 } }); } }).start();}
时间: 2024-10-26 21:50:40