Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find parent view by id

Tags:

java

android

I have a little complex layout and I add a tag to the SwitchLayout of this view.

There is an ImageButton inside this view. Here is a little map to this button:

LinearLayout -> SwitchLayout -> RelativeLayout -> RelativeLayout -> ImageButton

At some point I want to get the tag attached to the SwitchLayout, but all I have is the reference to the ImageButton.

I've tried to look for an ID, but it seems that android is searching downwards only, so

imageButton.findViewById(R.id.switchLayout);

doesn't work.

It also looks like I can't get the assigned tag directly from the ImageButton.

This code:

imageButton.getTag()

returns null

The only one workaround I found is here, but it is ugly:

ViewSwitcher viewSwitcher = (ViewSwitcher)imageButton.getParent().getParent().getParent();
viewSwitcher.getTag();

I would like to make the coupling as week as possible, so I'm wondering if there is either a way to assign the Tag to the viewSwitcher and all of it's children,

Or findViewById among parent views.

like image 511
Vlad Spreys Avatar asked Dec 01 '22 20:12

Vlad Spreys


2 Answers

Why not just keep the reference of switch layout?

// In activity
switchLayout = findViewById(R.id.switchLayout);
imageButton = findViewById(R.id.imageButton);

If your method is still in the activity, you can directly access switchLayout, if not, you can set switchLayout to imageButton tag and read it later,

imageButton.setTag(switchLayout);

or if you really need to do this, you can do it recursively,

public ViewParent findParentRecursively(View view, int targetId) {
    if (view.getId() == targetId) {
        return (ViewParent)view;
    }
    View parent = (View) view.getParent();
    if (parent == null) {
        return null;
    }
    return findParentRecursively(parent, targetId);
}
like image 62
Qiang Jin Avatar answered Dec 04 '22 10:12

Qiang Jin


declare and define a reference to the swtichlayout and get the tag directly. why do u want to get the tag of switchlayout using the imagebutton.

like image 32
SKK Avatar answered Dec 04 '22 09:12

SKK