这是我的代码,但有 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。谁能找到更好的方法来做到这一点?