由于会用到RecyclerView这控件,需在app/build.gradle文件,在dependencies闭包添加
implementation 'com.android.support:recyclerview-v7:26.1.0'
布局代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lin.swiperefreshlayout.MainActivity">
<!--SwipeRefreshLayout实现下拉刷新的功能-->
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/swipeRefresh"
>
<!--展示数据的列表-->
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
MainActivity的代码
public class MainActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//进行初始化
initView();
}
private void initView() {
swipeRefresh = findViewById(R.id.swipeRefresh);
//改变下拉进度条刷新的颜色
swipeRefresh.setColorSchemeColors(Color.RED);
//下拉刷新的监听器
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//onRefresh()方法应该进行网络上的数据情况,不过为简单模拟,就调用线程睡了两秒
refresh();
}
});
}
private void refresh() {
new Thread(){
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
//隐藏进度条
swipeRefresh.setRefreshing(false);
Toast.makeText(MainActivity.this,"刷新完成",Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
}