android - 在同一个 Activity 中的 Fragment 之间传递数据

标签 android android-fragments

我在一个项目中工作,该项目有一个托管许多 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/

相关文章:

android - 以编程方式打开/关闭 ShapeDrawable (RectShape) 的闪烁/翻转动画/效果

java - 如何在 android 'java' 中将位图对象转换为图像对象,反之亦然

android - 在 AsyncTask 中保留对 Fragment 的强引用是否安全?

android - 重新创建包含 fragment 时未加载 ViewPager 中的 fragment

android - 如何使用 Android DialogFragment setStyle()

java - Android - DialogFragment 从 Fragment 中显示。 DialogFragment 关闭时如何显示 Fragment 中的 Toast?

Android - Fragment 和 Activity 的关系

java - ADB 不起作用...Eclipse 未检测到我的设备

android - 如何防止未启用的 EditText 出现键盘

c# - 开发Unity增强现实vuforia应用并与原生android应用集成