Created
August 21, 2015 08:57
-
-
Save jnagels/702bb6e5ddaa4ec3f8be to your computer and use it in GitHub Desktop.
ViewPager that draws the children in the correct order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package android.support.v4.view; | |
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.view.View; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
/** | |
* Viewpager that will draw childview in the order of the adapter. | |
*/ | |
public class CorrectChildDrawingViewPager extends ViewPager | |
{ | |
private ArrayList<View> mDrawingOrderedChildren; | |
private final PositionComparator sPositionComparator = new PositionComparator(); | |
public CorrectChildDrawingViewPager(Context context) | |
{ | |
super(context); | |
} | |
public CorrectChildDrawingViewPager(Context context, AttributeSet attrs) | |
{ | |
super(context, attrs); | |
} | |
@Override | |
protected int getChildDrawingOrder(int childCount, int i) | |
{ | |
final int result = ((LayoutParams) mDrawingOrderedChildren.get(i).getLayoutParams()).childIndex; | |
return result; | |
} | |
@Override | |
void populate(int newCurrentItem) | |
{ | |
super.populate(newCurrentItem); | |
//sort the children. | |
this.sortChildDrawing(); | |
} | |
/** | |
* Sort our children, this is copied from inside ViewPager. | |
*/ | |
private void sortChildDrawing() | |
{ | |
if (mDrawingOrderedChildren == null) | |
{ | |
mDrawingOrderedChildren = new ArrayList<>(); | |
} | |
else | |
{ | |
mDrawingOrderedChildren.clear(); | |
} | |
final int childCount = getChildCount(); | |
for (int i = 0; i < childCount; i++) | |
{ | |
final View child = getChildAt(i); | |
mDrawingOrderedChildren.add(child); | |
} | |
Collections.sort(mDrawingOrderedChildren, sPositionComparator); | |
} | |
class PositionComparator implements Comparator<View> | |
{ | |
@Override | |
public int compare(View lhs, View rhs) | |
{ | |
final LayoutParams llp = (LayoutParams) lhs.getLayoutParams(); | |
final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams(); | |
if (llp.isDecor != rlp.isDecor) | |
{ | |
return llp.isDecor ? 1 : -1; | |
} | |
//LayoutParams.position is only set in certain locations. | |
//Use ItemInfo.position which has the correct position | |
final ItemInfo lii = infoForChild(lhs); | |
final ItemInfo rii = infoForChild(rhs); | |
return lii.position - rii.position; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment