HarmonyOS 鸿蒙Next下拉刷新 SwipeRefreshLayout

HarmonyOS 鸿蒙Next下拉刷新 SwipeRefreshLayout

下拉刷新 SwipeRefreshLayout

  1. 添加依赖
implementation("androidx.swiperefreshlayout:swiperefreshlayout:1.1.0")
  1. 把想要实现下拉功能的控件放到SwipeRefreshLayout中
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/swipeRefreshLayout"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
  1. 添加刷新逻辑
swipeRefresh=binding.swipeRefreshLayout
swipeRefresh.setColorSchemeResources(R.color.colorPrimary) //给刷新的进度条设置颜色
swipeRefresh.setOnRefreshListener { //设置监听器,当用户下拉刷新时就会回调这里的lambda表达式
    refreshFruit(adapter)
}

private fun refreshFruit(adapter: FruitAdapter){
    thread{
        Thread.sleep(2000)
        runOnUiThread {
            initFruit()
            adapter.notifyDataSetChanged()
            swipeRefresh.isRefreshing=false //表示刷新事件结束并隐藏刷新进度条
        }
    }

}

更多关于HarmonyOS 鸿蒙Next下拉刷新 SwipeRefreshLayout的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS中实现下拉刷新可以使用RefreshContainer组件。这是鸿蒙Next推荐的下拉刷新容器,替代了Android的SwipeRefreshLayout。使用时需在ability_main.xml中声明RefreshContainer,并绑定RefreshController控制刷新状态。通过onRefreshing回调处理刷新逻辑,完成后调用finishRefresh()结束刷新动画。该组件支持自定义刷新头部样式,需继承RefreshAnimator类实现。

更多关于HarmonyOS 鸿蒙Next下拉刷新 SwipeRefreshLayout的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中实现下拉刷新功能,可以使用RefreshContainer组件替代Android的SwipeRefreshLayout。以下是实现方式:

  1. XML布局中使用RefreshContainer:
<RefreshContainer
    ohos:id="$+id:refreshContainer"
    ohos:width="match_parent"
    ohos:height="match_parent">
    
    <ListContainer
        ohos:id="$+id:listContainer"
        ohos:width="match_parent"
        ohos:height="match_parent"/>
</RefreshContainer>
  1. Java代码中设置刷新监听:
RefreshContainer refreshContainer = (RefreshContainer) findComponentById(ResourceTable.Id_refreshContainer);
refreshContainer.setRefreshListener(() -> {
    // 执行刷新操作
    getUITaskDispatcher().delayDispatch(() -> {
        // 刷新完成后调用
        refreshContainer.finishRefresh();
    }, 2000);
});
  1. 特性说明:
  • 自带默认刷新动画效果
  • 支持自定义刷新头部
  • 可通过setRefreshEnabled()控制是否启用刷新
  • 调用finishRefresh()结束刷新状态

注意:HarmonyOS Next的RefreshContainer是原生组件,不需要额外添加依赖库。

回到顶部