ATES
ATES

Reputation: 337

Recyclerview Layout Manager Get View in Position After Scrolling in Android

Recyclerview is scrolling with it's LinearLayoutManager like that lm.scrollToPositionWithOffset(position, offset). How to get the view where in scrolled position before scrolling? The view that will scrolled returning null after scrolling because still not created. I've try Runnable, Observer and onLayoutCompleted but still null. How to get the view?

lm.scrollToPositionWithOffset(position, offset);

recyclerView.post(new Runnable(){
    @Override
    public void run(){
        View v1 = recyclerView.getChildAt(position); // returning null.
        View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
    }
});

recyclerView.getViewTreeObserver()
   .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
       @Override
       public void onGlobalLayout() {
           View v1 = recyclerView.getChildAt(position); // returning null.
           View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
       recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}});

@Override // in LinearLayoutManager
public void onLayoutCompleted(RecyclerView.State state) {
    super.onLayoutCompleted(state);
    View v1 = recyclerView.getChildAt(position); // returning null.
    View v2 = this.getChildAt(position); // returning null.  
}

Upvotes: 2

Views: 972

Answers (2)

Pleaser
Pleaser

Reputation: 576

View v = lm.getChildAt(position);
lm.scrollToPositionWithOffset(position, offset);
v.post(new Runnable() {
    @Override
    public void run() {
        // View is ready here.                
});

Upvotes: 1

Ezequiel Zanetta
Ezequiel Zanetta

Reputation: 74

If you're trying to modify the view content, you should do this:

  1. Modify your current model: itemList.get(position) // and change any property here to handle that state

  2. Call adapter.notifyItemChanged(position)

  3. Make sure you have the right logic on your ViewHolder to handle this changes and that should modify your View

But if you really wanna change things through the ViewHolder you can also do this: recyclerView.findViewHolderForAdapterPosition(position) and then:

if (null != holder) { holder.itemView.findViewById(R.id.YOUR_ID) // call any method do you want to }

I really recommend the first option, but that's up to you. Hope this helps you!

Upvotes: 1

Related Questions