2012-02-03 64 views
6

例如,在列表视图中,由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个片段一个活动,使片段交易象下面这样:

// 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开发者网页,还有如何使用片段以及如何与活动通信的good document,但没有关于如何将数据从一个片段转移到另一个....

+1

可能重复的[Android:传递数据(额外)到片段](http://stackoverflow.com/questions/15392261/android-pass-dataextras-to-a-fragment) – 2014-02-16 13:45:59

回答

22

描述使用

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

你的意思是我没有需要在片段中定义接口,并让主机活动实现在片段和主机acvitity之间建立通信的接口......相反,我可以使用您的代码直接导航到下一个片段? – 2012-02-03 12:03:35

+0

是的,你可以直接使用它.... – 2012-02-03 12:38:46

+0

@its不是空白你可以请更多的灯光.navigateTo(片段); Android工作室似乎并不承认这 – archon92 2015-01-11 06:44:34

1

从你的活动意图发送数据为:

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

和片段onCreateView方法:

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

我希望这对你有帮助。

相关问题