2

我有一个GridView充满了图像,当你点击其中一个图像时,它开始了一个detais活动。
这一切工作正常,但现在我想做一个主 - 布局布局。所以,我创建了“布局,土地”文件夹,而不是只有一个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> 


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

+2

的[与其它片段进行通信(http://developer.android.com/training/basics/fragments/communicating.html)文档是我发现主从片段的最简单的例子。 –

回答

1

简单的片段。

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

我发布了另一个SO链接的完整答案@Passing data between fragments contained in an activity。只需找到我的用户名,这是该帖子的唯一答案。让我们知道你的进步。

+1

如果这是重复的,你应该按照这样的方式进行投票,而不是发布仅指向其他帖子的仅链接答案。 –

+0

@MikeM。我下次再考虑一下。我不愿意投任何职位为重复职位,然后可能会被其他人投票结案。我记得有一次,我实际上不同意别人在另一篇文章中的看法。 –

0

既然你已经在布局一个静态的片段,我想你不会删除,我会说使用一个简单的逻辑是这样的:

在你的活动中,创建将更新您的静态fragment等的方法:

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

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

并在你的片段中加载你的图片在你的ImageView(你应该有一个)。

0

按方格使用EventBus。

创建总线对象和活动进行注册

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

与参数作为模型创建活动public方法。

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

GridViewonItemClick发布项目 -

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

你可以找到使用

Fragment fragment = getFragmentManager().findFragmentById(R.id.fragmentLoadingSpace) 
if(fragment instanceof Fragment1){ 
    ((Fragment1) fragment).updateSelectedObjec(Objects object); 
} 
相关问题