bcsta
bcsta

Reputation: 2327

Android how to get an ancestor view from a child view?

I have a list of type Foo with a custom array Adapter. I want to be able to click on a child element in one of the views in the array adapter and get back the view I clicked on of type Foo.

This is how I am clicking on a child element:

// fill array with a test set of objects
final ArrayList<Foo> locations = Foo.getTestingList();

final myCustomArrayAdapter adapter = new myCustomArrayAdapter(rootView.getContext(), myarrayList);
         adapter.setDefaultRequestBtnClickListener(new View.OnClickListener(){
             @Override
             public void onClick(View v){
                    //if child element is clicked
                    if(v.getId() == R.id.deleteBTN){
                        //tag is set to the position in my custom adapter
                        int pos = (Integer)v.getTag();

                       //Get this child's parent view (type foo)


                    }

             }
         });

I want to be able to use certain Foo methods on the Fooparent of the child View I just clicked on.

Upvotes: 0

Views: 1482

Answers (1)

cincy_anddeveloper
cincy_anddeveloper

Reputation: 1152

If you wanna get the direct parent of a view, you can call the method getParent() and it will return immediate parent of the target view. Note, this method doesn't directly return a view but instead a ViewParent. ViewParent does not technically need to be a View but all views capable of holding child views i.e. a "view parent" in the Android SDK are of type ViewGroup which itself implements the ViewParent. So in reality virtually all ViewParents are a ViewGroup, which in itself is a View.

Furthermore, if you wanna access an ancestor view that's beyond the direct parent, you can recursively call getParent() and perform checks on the return parent view to determine if they are the desired view.

Upvotes: 1

Related Questions