android listview上拉刷新,新数据在前
时间: 2023-06-20 16:08:54 浏览: 116
Android ListView 下拉刷新、上拉加载
实现 Android ListView 上拉刷新,并且让新数据在前面可以使用下拉刷新框架 SwipeRefreshLayout 和 RecyclerView。
1. 添加 SwipeRefreshLayout 和 RecyclerView
```xml
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
```
2. 设置下拉刷新监听器
```java
SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// 执行刷新操作
// ...
}
});
```
3. 设置 RecyclerView 布局管理器和适配器
```java
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
```
4. 监听 RecyclerView 滚动事件,触发上拉加载更多
```java
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager.findLastVisibleItemPosition() == adapter.getItemCount() - 1) {
// 执行加载更多操作
// ...
}
}
});
```
5. 将新数据插入到 RecyclerView 的顶部
```java
adapter.addData(0, newData);
```
6. 结合下拉刷新和上拉加载更多实现完整的列表刷新
```java
private void refreshData() {
// 加载最新数据
// ...
swipeRefreshLayout.setRefreshing(false);
}
private void loadMoreData() {
// 加载更多数据
// ...
}
SwipeRefreshLayout swipeRefreshLayout = findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshData();
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager.findLastVisibleItemPosition() == adapter.getItemCount() - 1) {
loadMoreData();
}
}
});
```
这样做可以实现在 Android ListView 上拉刷新,并且让新数据在前面。
阅读全文