Android上拉加载更多
时间: 2023-10-25 15:08:13 浏览: 92
Android 加载更多
4星 · 用户满意度95%
在Android中实现下拉刷新和上拉加载更多可以使用第三方库,比如SwipeRefreshLayout和RecyclerView,下面是一个简单的示例:
1.在布局文件中添加RecyclerView和SwipeRefreshLayout:
```
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
```
2.在Activity或Fragment中设置RecyclerView的LayoutManager和Adapter,并为SwipeRefreshLayout设置刷新监听器。示例代码如下:
```
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeRefreshLayout;
private MyAdapter adapter;
private List<String> dataList = new ArrayList<>();
private int page = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
// 设置布局管理器
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// 设置adapter
adapter = new MyAdapter(dataList);
recyclerView.setAdapter(adapter);
// 设置刷新监听器
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// 下拉刷新操作
refresh();
}
});
// 设置滑动监听器,实现上拉加载更多
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();
int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int totalItemCount = layoutManager.getItemCount();
if (lastVisibleItemPosition == totalItemCount - 1 && dy > 0) {
// 上拉加载更多
loadMore();
}
}
});
// 第一次进入页面时自动刷新
swipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
refresh();
}
});
}
// 下拉刷新
private void refresh() {
page = 1;
dataList.clear();
getDataList();
}
// 上拉加载更多
private void loadMore() {
page++;
getDataList();
}
// 模拟获取数据
private void getDataList() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
dataList.add("item " + (dataList.size() + 1));
}
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 2000);
}
```
在上述代码中,refresh()方法用于下拉刷新,loadMore()方法用于上拉加载更多,getDataList()方法用于获取数据。在getDataList()方法中,我们使用Handler模拟了一个异步任务,通过adapter.notifyDataSetChanged()方法来更新RecyclerView的显示。
阅读全文