问题
this is my child fragment and how to access my parent fragment from this fragment please help me to 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 error while run the project
java.lang.IllegalArgumentException: No view found for id 0x7f0c0099 (com.knrmarine.knr:id/containerView) for fragment EnquiryActivity{3754711 #2 id=0x7f0c0099}
This my Enquiryfragment
code :
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;}}
回答1:
You can get parent Fragment
's reference by :
ParentFragment parentFrag = ((ParentFragment)ChildFragment.this.getParentFragment());
parentFrag.someMethod();
I used this in my ViewPager. If you have other requirement, Interface
or EventBus
are two of the general ones.
回答2:
Late answer but there is a quite simple way to access a fragment's parent fragment :
Kotlin
(parentFragment as YourParentFragment).parentFragmentMethod()
Java
((YourParentFragment) getParentFragment()).parentFragmentMethod();
回答3:
Access Parent Fragment Method from Child Fragment
((YourParentFragmentName) getParentFragment()).yourParentFragmentMethod();
Access Child Fragment Method from Parent Fragment
YourChildFragmentName fragment = (YourChildFragmentName) getChildFragmentManager().getFragments().get(positionOfYourChildFragment);
fragment.yourChildFragmentMethod();
回答4:
Above method did not worked for me (API 26). I found out a new solution here:
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentByTag("MyFragment");
if(fragment != null && fragment instanceof MyFragment)
((MyFragment) fragment).someMethod();
else
Log.e(TAG, "cannot change tab its null...");
来源:https://stackoverflow.com/questions/42695866/access-parent-fragment-by-child-fragment