[英]Android ViewModel load more data when Fragment scroll reaches end
我是 Android 的新手,所以不知道該怎么做
我有一個帶有列表視圖的片段。 我需要片段能夠檢測到列表視圖滾動到達末尾,為此我可以執行以下操作
listView.setOnScrollListener(onScrollListener());
private OnScrollListener onScrollListener() {
return new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition()>=count-threshold&&pageCount < 2)
{
Log.i(TAG, "loading more data");
// Execute LoadMoreDataTask AsyncTask
getDataFromUrl(url_page2);
}
}
}
}
}
但是,在上面的代碼中,我們使用了本地方法 getDataFromUrl ,而不是我需要告訴 ViewModel 加載更多數據並使用 LiveData 更新片段
創建您自己的滾動監聽器。
public abstract class EndlessScrollListener extends RecyclerView.OnScrollListener {
private int visibleThreshold = 2;
private int currentPage = 1;
private int previousTotalItemCount = 0;
private boolean loading = true;
private RecyclerView.LayoutManager mLayoutManager;
// it can LinearLayoutManager as well
public EndlessScrollListener(GridLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
int totalItemCount = mLayoutManager.getItemCount();
int lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
}
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
currentPage++;
onLoadMore(currentPage, totalItemCount, view);
loading = true;
}
}
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
}
在片段 class
private void observeEndlessScrolling() {
scrollListener = new EndlessScrollListener(layoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
viewModel.fetchMoreData(page);
}
}
};
recyclerView.addOnScrollListener(scrollListener);
}
在你的片段中
yourViewModel.getDataFromUrl().observe(this, new Observer<ArrayList<Slider>>() {
@Override
public void onChanged(ArrayList<YourDataType> datasServer) {
//when data changes you get here...so notify adapter accordingly
}
});
這將觀察您的 ViewModel 中的數據變化
在您的 ViewModel 中創建此數據類型
private MutableLiveData<ArrayList<YourDataType>> data;
private ArrayList<YourDataType> serverDatas= new ArrayList<>();
現在,在您的 viewModel 和您的內部創建 getDataFromUrl()
來自服務器的 response(...) 創建一個循環並將數據添加到 AttayList serverDatas:
YourDataType yourDataType = new YourDataType(....);
serverDatas.add(yourDataType);
最后
data.setValue(serverDatas);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.