例如,我有2个片段,包括1个整数变量和1个TextView。其中一个有一个按钮。我希望此按钮可以更改所有整数和TextView,包括其他片段。如何访问其他片段的Variable和TextView?请用示例代码解释。
答案 0 :(得分:1)
片段到片段通信基本上是通过一个活动来实现的,该活动通常托管片段,在片段A中定义一个接口,让你的Activity实现该接口。现在,您可以调用Fragment中的接口方法,并且您的Activity将接收该事件。现在,在您的活动中,您可以调用第二个片段以使用收到的值更新textview(例如):
// 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
}
}