如何在片段之间传递数据 [英] How to pass data between fragments

查看:58
本文介绍了如何在片段之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的程序中的两个片段之间传递数据.它只是一个存储在列表中的简单字符串.列表在片段 A 中公开,当用户单击列表项时,我需要它显示在片段 B 中.内容提供者似乎只支持 ID,所以这行不通.有什么建议吗?

Im trying to pass data between two fragmens in my program. Its just a simple string that is stored in the List. The List is made public in fragments A, and when the user clicks on a list item, I need it to show up in fragment B. The content provider only seems to support ID's, so that will not work. Any suggestions?

推荐答案

为什么不使用 Bundle.从您的第一个片段开始,以下是设置方法:

Why don't you use a Bundle. From your first fragment, here's how to set it up:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

然后在您的第二个 Fragment 中,使用以下方法检索数据:

Then in your second Fragment, retrieve the data using:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

Bundle 有很多数据类型的 put 方法.请参阅 http://developer.android.com/reference/android/os/Bundle.html

Bundle has put methods for lots of data types. Please see http://developer.android.com/reference/android/os/Bundle.html

这篇关于如何在片段之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆