Find current view in ViewPager

A hack to find the current view (index) in a ViewPager

Note: ViewPager.getCurrentItem() : if the ViewPager starts up on a view different from the first view, getCurrentItem() still returns the first position, i.e., 0, and will do so until the ViewPager has been paged.

private int getCurrentPageIndex(ViewPager vp){
    int first,second,id1,id2,left;
    id1 = first = second = 99999999;
    View v;
    for ( int i = 0, k = vp.getChildCount() ; i < k ; ++i ) {
        left = vp.getChildAt(i).getLeft();
        if ( left < second ) {
            if ( left < first ) {
                second = first;
                id2 = id1;
                first = left;
                id1 = i;
            } else {
                second = left;
                id2 = i;
    return id2;


Java rounding up to an int using Math.ceil


int total = (int) Math.ceil(157/32);

Why does it still return 4? 157/32 = 4.90625, I need to round up, I’ve looked around and this seems to be the right method.

I tried total as double type, but get 4.0.

What am I doing wrong?



You are doing 157/32 which is dividing two integers with each other, which always result in a rounded down integer. Therefore the (int) Math.ceil(...) isn’t doing anything. There are three possible solutions to achieve what you want. I recommend using either option 1 or option 2. Please do NOT use option 0.

Continue reading