[英]RecyclerView scroll to position of child view's child
這是我的代碼,但是有NullPointerException
public class ViewMenu extends LinearLayout {
protected Handler mHandler;
@BindView(R.id.recycler)
protected RecyclerView mRecycler;
//...
@Override
protected void onFinishInflate() {
super.onFinishInflate();
ButterKnife.bind(this);
mHandler = new Handler();
mRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
//...
Message msg=new Message();
msg.what=1;
Bundle bundle=new Bundle();
bundle.putInt("targetPosition",3);//assume this is a valid position
bundle.putInt("targetChild",2);//assume this is a valid child
msg.setData(bundle);
handler.sendMessage(msg);
}
class Handler extends android.os.Handler {
@Override
public void handleMessage(Message msg) {
int targetPosition=msg.getData().getInt("targetPosition");
int targetChild=msg.getData().getInt("targetChild");
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecycler.getLayoutManager();
ViewGroup targetViewGroup = (ViewGroup) layoutManager.findViewByPosition(targetPosition);//targetViewGroup becomes null
View targetView = targetViewGroup.getChildAt(targetChild);//NullPointerException
layoutManager.scrollToPositionWithOffset(targetPosition, targetView.getLeft());
}
}
}
我認為問題在於,當targetViewGroup不可見時,findViewByPosition返回null。 有人能找到更好的方法嗎?
最后我自己解決了。 我猜的原因是當您調用layoutManager.scrollToPositionWithOffset()方法時,滾動事件被發送到處理程序。 在循環程序收到消息之前,回收者視圖將不會進行真正的滾動。 因此正確的方法是在調用scrollToPositionWithOffset()之后使用handler.post()。
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecycler.getLayoutManager();
//scroll to make the target page visible
if (page < layoutManager.findFirstVisibleItemPosition())
//if the target page is in left and invisible, post: scroll to show one pixel in the screen left
layoutManager.scrollToPositionWithOffset(page + 1, 1);
else if (page > layoutManager.findLastVisibleItemPosition())
//if the target page is in right and invisible, post: scroll to show one pixel in the screen right
layoutManager.scrollToPositionWithOffset(page, mRecycler.getWidth() - mRecycler.getPaddingLeft() - mRecycler.getPaddingRight() - 1);
//post: scroll to candidate
getHandler().post(() -> {
ViewGroup pageView = (ViewGroup) mRecycler.findViewHolderForAdapterPosition(page).itemView;
View candView = pageView.getChildAt(cand);
layoutManager.scrollToPositionWithOffset(page, left ? candView.getLeft() : candView.getRight());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.