我在一个项目中工作,该项目有一个托管许多 fragment 的 Activity 。现在我需要在这些 fragment 之间共享一些数据(整数、字符串、数组列表)。
我第一次使用静态字段,但我认为这是一种糟糕的方式 然后我找到了this solution .
但在我的例子中没有按钮可以点击我只能在 fragment 之间导航 有什么简单的方法可以在 fragment 之间共享数据
最佳答案
我认为最适合您的解决方案是将变量放在主要 Activity 中并从 fragment 中访问它们。我的意思是,如果您必须在所有 fragment 中执行相同的操作,您可以在 Activity 中编写代码并调用您需要的方法。
为此你需要使用一个接口(interface)
public interface DataCommunication {
public String getMyVariableX();
public void setMyVariableX(String x);
public int getMyVariableY();
public void setMyVariableY(int y);
}
然后,在你的 Activity 中实现它
public class MainActivity extends Activity implements DataCommunication {
private String x;
private int y;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
...
@Override
public String getMyVariableX(){
return x;
}
@Override
public void setMyVariableX(String x){
//do whatever or just set
this.x = x;
}
@Override
public int getMyVariableY(){
return y;
}
@Override
public void setMyVariableY(int y){
//do whatever or just set
this.y = y;
}
...
然后,将 Activity 附加到您的所有 fragment 中:
public class Fragment_1 extends Fragment{
DataCommunication mCallback;
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (DataCommunication) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement DataCommunication");
}
}
...
最后,当您需要在 fragment 中使用变量时,只需使用您创建的 get 和 se 方法
https://developer.android.com/training/basics/fragments/communicating.html
关于android - 在同一个 Activity 中的 Fragment 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38331816/