Access to parent fragment by child fragment

this is my child fragment and how to access my parent fragment from this fragment please help me fix it

public class Profilefragmant extends Fragment {
public Profilefragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.profile_layout, container, false);

    TextView VE = (TextView) rootView.findViewById(R.id.profile_view_enquiry);
    VE.setOnClickListener(new View.OnClickListener(){
        public void onClick (View view){
            Fragment fragment = null;

            fragment = new Enquiryfragment();
            replaceFragment(fragment);
        }
    });



    return rootView;
}
public void replaceFragment(Fragment someFragment) {
    android.support.v4.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.containerView, someFragment);
    transaction.addToBackStack(null);
    transaction.commit();
}
}

this is my mistake when starting a project

 java.lang.IllegalArgumentException: No view found for id 0x7f0c0099 (com.knrmarine.knr:id/containerView) for fragment EnquiryActivity{3754711 #2 id=0x7f0c0099} 

This is my code Enquiryfragment:

public class Enquiryfragmant extends Fragment {
public Enquiryfragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.enquiry_layout, container, false);
return rootView;}}
+15
source share
4 answers

You can get the original link Fragment:

ParentFragment parentFrag = ((ParentFragment)ChildFragment.this.getParentFragment());
parentFrag.someMethod();

I used this in my ViewPager. If you have another requirement, Interfaceor EventBusare two of the common ones.

+40
source

Late answer, but there is a pretty simple way to access the fragment of the parent fragment:

Kotlin

(parentFragment as YourParentFragment).parentFragmentMethod()

Java

((YourParentFragment) getParentFragment()).parentFragmentMethod();
+5
source

(API 26). :

Fragment fragment = getActivity().getSupportFragmentManager().findFragmentByTag("MyFragment");

if(fragment != null && fragment instanceof MyFragment)
     ((MyFragment) fragment).someMethod();
else
     Log.e(TAG, "cannot change tab its null...");
0

Access the parent fragment method from the child fragment

((YourParentFragmentName) getParentFragment()).yourParentFragmentMethod();

Access the method of the child fragment from the parent fragment

YourChildFragmentName fragment = (YourChildFragmentName) getChildFragmentManager().getFragments().get(positionOfYourChildFragment);
fragment.yourChildFragmentMethod();
0
source

Source: https://habr.com/ru/post/1671888/


All Articles