首先要导个SwipyRefreshLayoutLibrary Module
然后在XML文件里布局,必须入下代码一样:
<com.bawei.swiperefreshlayoutlibrary.SwipyRefreshLayout android:id="@+id/sw" android:layout_width="match_parent" android:layout_height="match_parent" > 把RecyclerView包含进来
</com.bawei.swiperefreshlayoutlibrary.SwipyRefreshLayout>
然后再MainActrivity里代码 如下:
private SwipyRefreshLayout srl;
private Handler handler = null;
private int page = 1;
private RecyclerView rv;
private List<NewsInfo.ResultsBean> lists = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
srl = (SwipyRefreshLayout) findViewById(R.id.srl);
rv = (RecyclerView) findViewById(R.id.rv);
//设置刷新控件颜色
srl.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark, android.R.color.darker_gray);
srl.setDirection(SwipyRefreshLayoutDirection.BOTH);
srl.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh(int index) {//下拉刷新
page = 1;
handler.postDelayed(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下拉刷新", Toast.LENGTH_SHORT).show();
getData(page);
srl.setRefreshing(false);
}
}, 2000);
}
@Override
public void onLoad(int index) {//上拉加载
page++;
Toast.makeText(MainActivity.this, "上拉加载", Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
@Override
public void run() {
getData(page);
srl.setRefreshing(false);
}
}, 2000);
}
});
}
private void getData(final int page) {
String url = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/" + page;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String json = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Gson gson = new Gson();
NewsInfo newsInfo = gson.fromJson(json, NewsInfo.class);
List<NewsInfo.ResultsBean> results = newsInfo.getResults();
if (page == 1) {
lists = new ArrayList<NewsInfo.ResultsBean>();
}
//累加数据源
lists.addAll(results);
//操作适配器
}
});
}
});
}
}