Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the index of a child view in android

I have a TableRow that contains TextViews. When a TextView is clicked, a method receives the the TextView. Is there a way to know if this TextView is the first, second, or i'th child of its parent view?

Thanks

like image 699
Ammar Samater Avatar asked Dec 21 '15 21:12

Ammar Samater


2 Answers

First you need to get a reference to the parent view with .getParent(). Having the parent you can use indexOfChild(myView) to get the index of your view within the parent. In one row it looks like this:

int indexOfMyView = ((TableRow ) myView.getParent()).indexOfChild(myView);

This should work with any type of parent view:

int indexOfMyView = ((ViewGroup) myView.getParent()).indexOfChild(myView);
like image 95
Ivo Stoyanov Avatar answered Nov 06 '22 10:11

Ivo Stoyanov


In onclicklistener, Get the parent of TextView

TableRow r = (TableRow) ((ViewGroup) textView.getParent());
int position = r.indexOfChild(textView)

Hope this helps

like image 42
sha Avatar answered Nov 06 '22 10:11

sha