目录
可使用SwipeRefreshLayout(下拉刷新布局)创建需要刷新的界面。
1. 引入依赖
清单文件中添加SwipeRefreshLayout的依赖
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
2. 在XML中的使用
SwipeRefreshLayout下拉刷新布局的下级必须是可滚动的视图,如ScrollView、RecyclerView等。
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E6FBAC">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="2000dp"
android:text="Test"/>
</LinearLayout>
</ScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
3. 常用方法
- setOnRefreshListener : 设置刷新监听器。需要重写监听器OnRefreshListener的onRefresh()方法,该方法在下拉松开时触发。
- setRefreshing : 设置刷新的状态。true表示正在刷新,false表示结束刷新。
- isRefreshing :判断是否正在刷新。
- setColorSchemeColors :设置进度圆圈的圆环颜色。参数可设置多个颜色,每转一圈变换一次颜色。
- setProgressBackgroundColorSchemeColor :设置进度圆圈的背景颜色。
- setProgressViewOffset :设置进度圆圈的偏移量。第一个参数表示进度圈是否缩放,第二个参数表示进度圈开始出现时距顶端的偏移,第三个参数表示进度圈拉到最大时距顶端的偏移。
- setDistanceToTriggerSync :设置手势向下滑动多少距离才会触发刷新操作。
4. Java代码中使用
请注意,在实现的刷新监听器的onRefresh()方法中,进行刷新的部分为防止阻塞线程,需要放在子线程中执行。
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取下拉布局对象
SwipeRefreshLayout swipeRefreshLayout=findViewById(R.id.swipeRefreshLayout);
//设置进度圆圈颜色---每转一圈会变换一次颜色
swipeRefreshLayout.setColorSchemeColors(Color.RED,Color.GREEN,Color.BLUE);
//设置进度圆圈偏移量---参数:是否缩放,首次出现位置,最大出现位置(单位:像素)
swipeRefreshLayout.setProgressViewOffset(true,10,100);
//设置触发刷新的滑动距离(单位:像素)
swipeRefreshLayout.setDistanceToTriggerSync(100);
//设置进度圆圈背景
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.white));
//设置监听器
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
public void onRefresh() {
//下拉刷新时调用
//此时swipeRefreshLayout.isRefreshing()返回true
//为防止阻塞主线程,需要在子线程中执行刷新操作
Thread thread=new Thread(new Runnable() {
public void run() {
//刷新操作(这里用线程Sleep代替)
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//刷新结束
swipeRefreshLayout.setRefreshing(false);
//此时swipeRefreshLayout.isRefreshing()返回false
}
});
thread.start();
}
});
}
}
tag:下拉刷新,下拉刷新布局,SwipeRefreshLayout,RecyclerView,循环控件,循环视图,ScrollView,滚动控件,滚动视图,刷新,列表,list