7

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.

ali-star
  • 706
  • 1
  • 10
  • 19

4 Answers4

18

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.

Anmol
  • 8,110
  • 9
  • 38
  • 63
1

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)
PSK
  • 583
  • 7
  • 15
0

Try this:

ParentFragment parent = (ParentFragment) getParentFragment();
parent.getView().findViewById(R.id.your_element);
Anton Sarmatin
  • 505
  • 2
  • 8
  • 3
    getParentFragment() method returns NavHostFragment, not my fragment. – ali-star Dec 20 '18 at 09:11
  • i tried that before but got error, androidx.navigation.fragment.NavHostFragment cannot be cast to alistar.navigation.fragments.DashboardFragment – ali-star Dec 20 '18 at 10:17
0

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!

Charan M
  • 489
  • 3
  • 7