安卓中的Material自带的下拉刷新控件,能实现下拉刷新的效果。

导入依赖:

1
2
3
4
dependencies {
...
implementation "androidx.swiperefreshlayout:swiperefreshlayout:$swiperefreshlayout_version"
}

引入布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/swipeRefresh">

<ScrollView
android:id="@+id/weatherLayout"
android:scrollbars="none"
android:overScrollMode="never"
android:visibility="invisible"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<include layout="@layout/now"/>
<include layout="@layout/forecast"/>
<include layout="@layout/life_index"/>

</LinearLayout>
</ScrollView>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

使用:

1
2
3
4
5
swipeRefresh.isRefreshing = false //设置刷新按钮是否显示可为true/false,通常在观察到livedata变化后就设为false
swipeRefresh.setColorSchemeResources(R.color.colorPrimary) //设置刷新按钮颜色
swipeRefresh.setOnRefreshListener {
//当下拉刷新时执行的逻辑,比如再次网络请求等
}

这样就可以很简单的实现一个下拉刷新功能了。