I have two fragments, Fragment A & B. Fragment B is included in Fragment A's xml.
for eg : fragment_a.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:clickable="true"
>
<fragment android:name="com.test.FragmentB"
android:id="@+id/fragment_b"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Now, I want to access method in Fragment B from Fragment A.
Eg : Fragment B :
public void releaseCamera(){
//todo: camera release here
}
Fragment A :
public void onButtonClick(){
//todo : call releaseCamera() here
//tried but didnot work
FragmentB fragmentB =
(FragmentB)getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_b);
fragmentB.releaseScannerCamera();
}
How can I achieve that? Should I use interface? Thanks,
FragmentB fragmentB = (FragmentB)getActivity().getFragmentManager().findFragmentById(R.id.fragment_b); fragmentB.releaseScannerCamera(this);
Found simple answer. Just had to use getChildFragmentManager(). No need to create any interface on activity as both fragments are directly connected from xml.
FragmentB fragmentB =
(FragmentB)getChildFragmentManager().findFragmentById(R.id.fragment_b);
fragmentB.releaseScannerCamera();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.