例如,我有 2 个片段,包括 1 个整数变量和 1 个 TextView。其中一个有一个按钮。我希望这个按钮更改所有整数和文本视图,包括其他片段。如何访问其他片段的变量和文本视图?请用示例代码进行解释。
片段到片段的通信基本上是通过通常托管片段的活动进行的,在片段 A 中定义一个接口,然后让您的活动实现该接口。现在,您可以在片段中调用接口方法,您的活动将收到该事件。现在在您的活动中,您可以调用第二个片段以使用接收的值更新文本视图(例如):
// You Activity implements your interface which is defined in FragmentA
public class YourActivity implements FragmentA.TextClicked{
@Override
public void sendText(String text){
// Get instance of Fragment B using FragmentManager
FraB frag = (FragB)
getSupportFragmentManager().findFragmentById(R.id.fragment_b);
frag.updateText(text);
}
}
// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{
TextClicked mCallback;
public interface TextClicked{
public void sendText(String text);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TextClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement TextClicked");
}
}
public void someMethod(){
mCallback.sendText("YOUR TEXT");
}
@Override
public void onDetach() {
mCallback = null; // => avoid leaking
super.onDetach();
}
}
// Fragment B has a public method to do something with the text
public class FragB extends Fragment{
public void updateText(String text){
// Here you have it
}
}