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.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With