Android:如何调用包含在XML中的片段的方法?

问题描述:

我有两个片段,片段A & B. 片段B包含在片段A的xml中。Android:如何调用包含在XML中的片段的方法?

为如: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> 

现在,我想从片段A.

如访问方法片段B: 片段B:

public void releaseCamera(){ 
//todo: camera release here 
} 

片段A :

public void onButtonClick(){ 
    //todo : call releaseCamera() here 
//tried but didnot work 
    FragmentB fragmentB = 
      (FragmentB)getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_b); 
    fragmentB.releaseScannerCamera(); 
} 

我该怎么做到这一点?我应该使用界面吗? 谢谢,

+0

从哪里添加这些A和B片段..?来自基地活动的 –

+0

。但这并不重要。您也可以为活动和片段提供解决方案。 Fragment包含在activity的xml中。现在我该如何访问该活动的片段方法? –

+0

首先你移除'fragment'标签并保留'FrameLayout'。 然后通过接口可以实现活动与片段或片段之间的通信以及片段。 –

FragmentB fragmentB = (FragmentB)getActivity()。getFragmentManager()。findFragmentById(R.id.fragment_b); 012-fragmentB.releaseScannerCamera(this);

  1. 永远不错的方法是使用FrameLayout代替Fragment。 使用add方法片段管理器从活动中添加这些(A和B)片段。
  2. 在活动中创建接口方法,它将返回片段A和B的对象。因此,您可以随时获取片段的对象,然后相应地调用这些方法。

找到简单答案。只需使用getChildFragmentManager()。无需创建任何活动接口,因为这两个片段都直接从xml连接。

FragmentB fragmentB = 
     (FragmentB)getChildFragmentManager().findFragmentById(R.id.fragment_b); 
fragmentB.releaseScannerCamera();