get Item Position within ListView - Android android.widget

Android examples for android.widget:ListView

Description

get Item Position within ListView

Demo Code

import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class Main{

    public static int getPositionAt(@NonNull ListView listView, int x, int y) {
        int firstPosition = listView.getFirstVisiblePosition();
        int lastPosition = listView.getLastVisiblePosition();
        for (int p = firstPosition; p <= lastPosition; p++) {
            View child = listView.getChildAt(p - firstPosition);
            if (child == null)
                continue;
            Rect hitRect = new Rect();
            child.getHitRect(hitRect);//w w w.  j a  v a2  s  . com
            if (hitRect.contains(x, y))
                return p;
        }
        return AdapterView.INVALID_POSITION;
    }

}

Related Tutorials