How to access a view of parent fragment from child fragment in navigation component

Viewed 8066

I need to access a view of parent fragment from child fragment. enter image description here

I have a graph inside a fragment (my parent fragment) and i want to access a view that present in the parent fragment from child fragment, i'm using android navigation component, it's confused me a little bit.

4 Answers

As i read your Explanation's You Know that ChildFragment Parent is NavHostFragment and NavHostFragment's Parent is ParentFragment.

NavHostFragment navHostFragment = (NavHostFragment) getParentFragment();
Fragment parent = (Fragment) navHostFragment.getParentFragment();
parent.getView().findViewById(R.id.element_id);

I have tried is my demo Project and work's for me.

Using Activity:

val buttonView = (context as Activity).findViewById<View>(R.id.map_list_card_view)

Using Fragment:

val parent: Fragment? = (parentFragment as NavHostFragment).parentFragment
val buttonView = parent?.view?.findViewById<View>(R.id.map_list_card_view)

Try this:

ParentFragment parent = (ParentFragment) getParentFragment();
parent.getView().findViewById(R.id.your_element);

Try this:

public class Fragment2 extends Fragment {
    View view;
    ...
    ...

    public void setView(View view) {
        this.view = view;
    }
}

And call mFragment.setView() before calling fragment transaction. I hope this helps!

Related