简体   繁体   中英

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 Foo parent of the child View I just clicked on.

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 ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM