简体   繁体   中英

Android : How to call method of fragment included in xml?

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);

  1. Always good approach is use FrameLayout instead Fragment. Add those(A and B) Fragment from activity using add method fragment manager.
  2. Create interface methods in activity which will return objects of Fragment A and B. So you can get the object of fragment whenever you want, and call those method accordingly.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM