繁体   English   中英

如何通过活动将额外数据从一个片段传输到另一个片段

[英]how to transfer extra data from one fragment to another through activity

例如,在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);
     }
}

应该怎么样如果我使用片段? 我的意思是如果我有一个Activity来托管2个片段,并进行如下的片段交易:

// 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开发者网页上,有一个很好的文档 ,说明如何使用片段以及如何与活动进行通信,但是没有关于如何将数据从一个片段传输到另一个片段的描述....

采用

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

从活动中您可以按意图发送数据:

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);
}

我希望对你有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM