Reputation: 183
I have a method in my fragment that looks like this:
private void getFirstVisibleMediaRecyclerView() {
int findFirstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
int findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int [] positions = { findFirstVisibleItemPosition, findLastVisibleItemPosition };
Rect scrollBounds = new Rect();
recyclerView.getDrawingRect(scrollBounds);
int[] location = new int[2];
for (int position : positions) {
RecyclerView.ViewHolder item = recyclerView.findViewHolderForAdapterPosition(0);
PostAdapter.PostViewHolder viewHolder = (PostAdapter.PostViewHolder) item;
viewHolder.mediaRecyclerView.getLocationInWindow(location);
if (location[1] < 0 || location[1] > scrollBounds.bottom) {
//
} else {
viewHolder.doSomething();
}
}
}
And my adapter class looks like this (I've removed parts that aren't important for this question):
public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public class PostViewHolder extends RecyclerView.ViewHolder {
public RecyclerView mediaRecyclerView;
public PostViewHolder(View v) {
super(v);
mediaRecyclerView = v.findViewById(R.id.media_recycler_view);
}
public void doSomething() {
LinearLayoutManager layoutManager = (LinearLayoutManager) mediaRecyclerView.getLayoutManager();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// LAYOUT MANAGER IS NULL HERE AND I DON'T KNOW WHY
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (layoutManager == null) {
return;
}
//
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
holder.mediaRecyclerView.setLayoutManager(layoutManager);
PostMediaAdapter mAdapter = new PostMediaAdapter(context, getData());
holder.mediaRecyclerView.setAdapter(mAdapter);
}
}
However, the layoutManager
in the doSomething()
method of the view holder is returning null
, and I have no idea why.
Please help!
Upvotes: 0
Views: 531
Reputation: 1135
First of all don't add layoutManager into onBindViewHolder you should add once your activity/fragment created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.id);
binding.rvList.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false))
}
because it effect performance of your application. try this remove form onBindViewHolder, what you want in doSomething() so I can suggest you need layoutManager object in adapter or its garbage.
Upvotes: 1