findFirstVisibleItemPositions не работает для recycleview android
у меня есть этот код:
mRecycleView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] firstVisibleItemPositions = new int[getResources().getInteger(R.integer.news_numbers_column)];
int pastVisiblesItems = ((StaggeredGridLayoutManager)getLayoutManager()).findFirstVisibleItemPositions(firstVisibleItemPositions)[0];
}
});
когда я прокручиваю свой recycleview, я получаю эту ошибку:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v7.widget.OrientationHelper.getStartAfterPadding()' on a null object reference
at android.support.v7.widget.StaggeredGridLayoutManager$Span.findOneVisibleChild(StaggeredGridLayoutManager.java:2177)
at android.support.v7.widget.StaggeredGridLayoutManager$Span.findFirstVisibleItemPosition(StaggeredGridLayoutManager.java:2153)
at android.support.v7.widget.StaggeredGridLayoutManager.findFirstVisibleItemPositions(StaggeredGridLayoutManager.java:806)
at info.lanouvelletribune.apps.android.ui.fragments.NewsFragment.onScrollStateChanged(NewsFragment.java:90)
at android.support.v7.widget.RecyclerView.setScrollState(RecyclerView.java:751)
at android.support.v7.widget.RecyclerView.onInterceptTouchEvent(RecyclerView.java:1535)
at com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView.onInterceptTouchEvent(ObservableRecyclerView.java:188)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2060)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2431)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2173)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2390)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1741)
at android.app.Activity.dispatchTouchEvent(Activity.java:2826)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2351)
at android.view.View.dispatchPointerEvent(View.java:8590)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4098)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3964)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3515)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3488)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3541)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3507)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3617)
at android
Как я могу справиться с этой ошибкой и получить первое видимое положение элемента?
6 ответов
я протестировал его с помощью этого кода, и он отлично работает со мной
int positionView = ((LinearLayoutManager)recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
я использовал параметр recycle view.
попробуйте это:
int position = layoutManager.findFirstVisibleItemPositions(null)[0];
здесь layoutManager
это то, что вы установили в своем recyclerview
.
например,
layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mrecyclerView.setLayoutManager(layoutManager );
вы можете использовать это :
int[] firstVisibleItemPositions = new int[yourNumberOfColumns];
int pastVisiblesItems = layoutManager.findFirstVisibleItemPositions(firstVisibleItemPositions)[0];
это ошибка в RecyclerView StaggeredGridLayoutManager:
https://code.google.com/p/android/issues/detail?id=180521
https://code.google.com/p/android/issues/detail?id=181461
обходным путем является попытка / поймать исключение:
try {
((StaggeredGridLayoutManager)getLayoutManager()).findFirstVisibleItemPositions(firstVisibleItemPositions);
} catch (NullPointerException ex) {
// workaround for RecyclerView bug. assume not laid out, so no items visible
firstVisibleItemPositions[0] = RecyclerView.NO_POSITION;
firstVisibleItemPositions[1] = RecyclerView.NO_POSITION;
}
Если вы используете StaggeredGridLayoutManager, вы можете найти findLastVisibleItemPositions, как показано ниже:
int visibleThreshold =1;
final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) mRecyclerViewAllPost.getLayoutManager();
mRecyclerViewAllPost.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] lastVisibleItemPositions = linearLayoutManager.findLastVisibleItemPositions(null);
int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
int totalItemCount = linearLayoutManager.getItemCount();
if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
print("load more item ");
isLoading = true;
}
}
});
и getLastVisibleItem метод, как показано ниже:
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
вы можете попробовать это так:
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
или вы можете использовать staggeredlayoutManager
объект непосредственно, вместо указанного выше объекта:
int[] into = staggeredGridLayoutManager .findLastVisibleItemPositions(null);
List<Integer> intoList = new ArrayList<>();
for (int i : into)
{
intoList.add(i);
}
int firstVisbleoitem= Collections.max(intoList);