So, I'm trying to change the height of a ImageView
in the onBindViewHolder
method of my recycler view depending on the height of another object in the same view holder. When I access the height with getHeight()
I get back 0 as a result for the first few elements - most probably because they are not drawn right now.
The general solution to this problem doesn't work for me, because the recycler view creates and binds a lot of views adding a GlobalLayoutListener
to each of them, which seems to mess the thing up giving me wrong results (e.g. just changing the height of the first element).
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolderDouble doubleHolder = (ViewHolderDouble) holder;
if (secProduct != null) {
final ViewTreeObserver observer = doubleHolder.linearLayoutSD.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int difference = doubleHolder.firstCardView.getHeight() - doubleHolder.secCardView.getHeight();
if (difference > 0) {
ImageView rightImage = doubleHolder.imageViewR;
rightImage.getLayoutParams().height = rightImage.getHeight() + difference;
rightImage.requestLayout();
} else if (difference < 0) {
ImageView leftImage = doubleHolder.imageViewL;
leftImage.getLayoutParams().height = leftImage.getHeight() + (difference * -1);
leftImage.requestLayout();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
doubleHolder.linearLayoutSD.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
doubleHolder.linearLayoutSD.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
}
}
Is there any way I can access the height of doubleHolder.firstCardView
& doubleHolder.secCardView
after the views are drawn, so I get the correct height and not 0?