Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

android - How to get location (on screen) of row in listview

I have implemented some gesture detection code so that I can detect when a row in my listview (which is situated in a FrameLayout) has been swiped.

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
        int itemId = MainActivity.this.getListView().pointToPosition((int) e1.getX(),(int) e1.getY());
        Offer order = (Offer)MainActivity.this.getListView().getAdapter().getItem(itemId);
        View v = MainActivity.this.getListView().getChildAt(itemId);
    }
}

I want to display a view over the top of the swiped row with a set of context sensitive options for that row.

My problems is that the following methods:

v.getTop()
v.getBottom()

return correct values only before the view has been scrolled. I could probably do some calculation to work out offsets using scroll positions etc but I also noticed that I only get values when I swipe a row that is visible on screen to begin with. If I scroll down the list and then swipe a row (that was not originally off-screen) then these methods return null values.

The methods below seem to suffer from the same problem...

v.getLocationOnScreen(loc)
v.getLocationInWindow(loc)

Ultimately, I am looking to find the distance between the top of the visible listView and the row that has been swiped. I will then use this distance to add a view to the parent FrameLayout with the appropriate height padding (so that it covers the swiped row).

Any help would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two different ways of indexing ListView items, by position in the adapter, or by visible place on the screen. An item will always be at the same position within the adapter (unless you alter the list). The index into view.getChildAt() will vary depending on what is visible on the screen.

The position being returned by pointToPosition is the position within the adapter. If you want to get the physical view, you need to account for if the view is scrolled. Try this:

int adapterIndex = MainActivity.this.getListView().pointToPosition((int) e1.getX(),(int) e1.getY());
int firstViewItemIndex = MainActivity.this.getListView().getFirstVisiblePosition();
int viewIndex = adapterIndex - firstViewItemIndex;
View v = MainActivity.this.getListView().getChildAt(viewIndex);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...