The requirement is that I want to highlight the first item of recycler view on my screen. I am using recyclerView.getChildAt(0) to get the first item but how do I figure out whether the first item of recycler view is available or not? I can't directly call getChildAt() because in some cases the network response might be slow and getChildAt(0) may return null.
Tried using onGlobalLayoutListener, didn't work.
CodePudding user response:
Why not highlight it in onBindViewHolder
of the adapter? You can check if the item is at position 0 or not and highlight accordingly. The adapter is responsible for the views anyway. You don't need to handle it outside the adapter class.
override fun onBindViewHolder(holder: YourHolderType, position: Int) {
//...
if (position == 0) {
// highlight the view in the holder
} else {
// de-highlight the view
}
}
CodePudding user response:
To find count of total items (instead of child-views), check like:
if (recyclerView.getAdapter().getItemCount() > 0) {
// Do something with items...
} else {
// No items, do something else?
}
Listener style
In case you are not sure when to do above check:
import androidx.recyclerview.widget.LinearLayoutManager;
// ...
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false){
@Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
// Your check should be here...
}
);