Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - Get x/y positions of nth item in RecyclerView

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"};

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);

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();

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...