安卓中的Material自带的下拉刷新控件,能实现下拉刷新的效果。
导入依赖:
groovy
dependencies {
...
implementation "androidx.swiperefreshlayout:swiperefreshlayout:$swiperefreshlayout_version"
}
引入布局:
xml
<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>
使用:
kotlin
swipeRefresh.isRefreshing = false //设置刷新按钮是否显示可为true/false,通常在观察到livedata变化后就设为false
swipeRefresh.setColorSchemeResources(R.color.colorPrimary) //设置刷新按钮颜色
swipeRefresh.setOnRefreshListener {
//当下拉刷新时执行的逻辑,比如再次网络请求等
}
这样就可以很简单的实现一个下拉刷新功能了。