20

I'm creating a table in which each row contains text as well as a button. Now when that button is pressed I want to call an event that uses the value of the text next to the button. How can I access the content of that TextView? I can get the ViewParent of my button, which should be the row, but there's no method to access that views children.

private OnClickListener updateButtonListener = new OnClickListener(){
     public void onClick(View v) {
         ViewParent parent = v.getParent();
         //Here I would like to get the first child of that ViewParent
      }
};
Lars
  • 523
  • 1
  • 6
  • 20

2 Answers2

66

If you can get a ViewParent, you can then cast it to a ViewGroup and get the View you need. Your code will look like this:

TextView textView = null;
ViewGroup row = (ViewGroup) v.getParent();
for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) {
    View view = row.getChildAt(itemPos);
    if (view instanceof TextView) {
         textView = (TextView) view; //Found it!
         break;
    }
}

That's it, assuming you have only one TextView in your row.

Malcolm
  • 41,014
  • 11
  • 68
  • 91
  • @Malcolm excellent answer. But if there are more than one textView then how to select a particular textView. – MDMalik Nov 07 '12 at 09:34
  • 3
    @MDMalik By using ids or tags. You should use different tags for the text views in the same view group, and when you find a text view, you get its tag and see if this is the view you need. – Malcolm Nov 07 '12 at 18:51
14

If you know the ID of a child element then you can do the following:

ViewGroup row = (ViewGroup) v.getParent();
TextView textView = (TextView) row.findViewById(R.id.childID);  
LarsH
  • 27,481
  • 8
  • 94
  • 152
Dmitry Grushin
  • 701
  • 5
  • 6