如何通过Activity从一个Fragment传输额外的数据到另一个Fragment

7
例如,在由ListActivity托管的列表视图中,当用户单击列表上的项目时,将启动新活动,并且先前的活动将向新活动传输额外的数据,如下所示:
public class Notepadv2 extends ListActivity {
    ...

   @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
     }
}

如果我使用片段,应该如何操作?我的意思是,如果我有一个托管2个片段的Activity,并进行如下的片段事务:
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

如何通过主活动将额外数据从一个片段传输到另一个片段?
我知道在Android开发者网页上,有一个很好的文档,介绍了如何使用片段和如何与活动通信,但没有关于如何在片段之间传递数据的说明...

1
可能是重复的问题:Android:将数据(extras)传递给片段 - Jim G.
2个回答

22
使用
Bundle data = new Bundle();
data.putString("name",value);
Fragment fragment = new nameOfFragment();
fragment.setArguments(data);
.navigateTo(fragment);

你的意思是说在Fragment中我不需要定义接口,而是让宿主Activity实现接口以建立Fragment和宿主Activity之间的通信... 然后,我就可以使用你的代码直接导航到下一个Fragment了? - Leem.fin
1
@不是空的。您能否详细说明一下.navigateTo(fragment);Android Studio似乎无法识别此内容。 - archon92
导航到是我的本地方法。 - Its not blank

4

从Activity中,您可以通过Intent发送数据:

Bundle bundle = new Bundle();
bundle.putString("key", "value");
// set Fragmentclass Arguments
Fragmentclass fragmentobj = new Fragmentclass();
fragmentobj.setArguments(bundle);

在 Fragment 的 onCreateView 方法中:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("key");    
    return inflater.inflate(R.layout.fragment, container, false);
}

我希望您能从中受益。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接