获取RecyclerView中第n个项目的x/y位置 [英] Get x/y positions of nth item in RecyclerView

查看:492
本文介绍了获取RecyclerView中第n个项目的x/y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在RecyclerView中获得第n个项目的X或Y位置.如果该项目当前在可见范围内,这很容易做到.但是,当视图当前不在屏幕上时(例如,RecyclerView上当前可见的项目范围是4到7,而我感兴趣的项目范围是1或10),似乎没有办法做到这一点.值.

I would like to know how to get the X or Y position of nth item in RecyclerView. This is easy to do if the item is currently within the visible range. However, when the view is currently off the screen (e.g., current visible items range on the RecyclerView is 4 to 7, while the item I am interested in is, say, 1 or 10), there seems to be no way to get that value.

这就是我尝试过的.我有以下三个字段:

Here's what I have tried. I have the following three fields:

private RecyclerView rv;

/* The Layout Manager of rv */
private LinearLayoutManager llm;

/* The data to be shown in the RecyclerView. */
private String[] data = {"0","1","2",...,"9"};

我在屏幕上显示了项目"2"到"5",并且我想获取当前不在屏幕上的项目"9"的X/Y位置.所以我尝试了以下方法:

I have the items "2" to "5" shown on the screen, and I want to get the X/Y position of the item "9", which is currently off the screen. So I tried the following:

int index = 9;
View v = rv.getChildAt(index);
View v2 = llm.getChildAt(index);

不幸的是,vv2均为空.原因似乎是,虽然data的大小为10,但rvllm的childCount还是屏幕上当前可见的视图数,如下所示:

Unfortunately, both v and v2 are null. The reason for it seems to be that while the size of data is 10, the childCount of rv and llm is whatever the number of views currently visible on the screen, as evidenced by the following:

int count = rv.getChildCount();
int count2 = llm.getChildCount();

两个变量均为4(当前可见的视图数;即"2"至"5").由于recyclerView的大小为4,并且我想在索引9处查找该项目,因此我在上面返回了null.

Both variables are 4 (the number of views currently visible; i.e., "2" to "5"). Since the size of the recyclerView is 4, and I want to look up the item at index 9, I get null returned above.

推荐答案

在回收器视图中,我使用以下命令对每个项目都得到了完美的xy:

I got perfect x and y of every item in recycler view using following:

int[] originalPos = new int[2];
view.getLocationInWindow(originalPos);
//or view.getLocationOnScreen(originalPos)
int x = originalPos[0];
int y = originalPos[1];

这篇关于获取RecyclerView中第n个项目的x/y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆