如何在屏幕上显示的 2 个片段之间传递数据?

How to pass data between 2 fragments displaying on the screen?

我有一个充满图像的 Gridview,当您单击其中一张图像时,它会启动一个详细信息 activity。
一切正常,但现在我想制作主从布局。所以我创建了那个 "layout-land" 文件夹,而不仅仅是一个 gridview,它是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
tools:context=".MainActivityFragment">

<GridView
    android:id="@+id/main_grid"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:numColumns="auto_fit" />

<fragment
    android:id="@+id/fragment"
    android:name="com.example.lucas.popularmovies.DetailActivityFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    tools:layout="@layout/fragment_detail" />

</LinearLayout>


在此之前,我将详细信息的数据作为意图的额外内容传递并在片段中检索它。
但是,当我在同一个屏幕上显示所有内容时,如何以一种方式传递数据,以便在我单击图像而不启动新的 activity 时更新详细信息?谢谢

我 post 在另一个 SO link @ Passing data between fragments contained in an activity 上编辑了一个完整的答案。只需找到我的用户名,这是 post 的唯一答案。让我们知道您的进展。

因为你的布局中有一个静态片段,我假设你不会删除它,我会说使用像这样的简单逻辑:

在您的 activity 中,创建一个方法来更新您的静态 fragment,例如:

public void updateImage(String imageUrl) {
    DetailActivityFragment fragment= (DetailActivityFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    if (fragment != null) {
        fragment.updateImage(imageUrl);
    }
}

无论何时单击图像,都会调用此方法。

然后在你的片段中加载你的图像到你的ImageView(你应该有一个)。

按方块使用EventBus。

创建总线对象并将其注册到Activity

Bus bus = new Bus();
bus.register(this);

在 Activity 中创建一个 public 方法,并将参数作为您的模型。

@Subscribe 
public void getDataFromGrid(MainGridItem item) {
    // TODO: React to the event somehow!
}

GridView onItemClick post 项目 -

bus.post(mainGridItems.get(position));

您可以使用

找到片段
Fragment fragment = getFragmentManager().findFragmentById(R.id.fragmentLoadingSpace)
if(fragment instanceof  Fragment1){
    ((Fragment1) fragment).updateSelectedObjec(Objects object);
}

简单。

DetailActivityFragment fragment= (DetailActivityFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
    if (fragment != null) {
        fragment.updateImage(url);
    }