【问题标题】:how to transfer extra data from one fragment to another through activity如何通过活动将额外数据从一个片段传输到另一个片段
【发布时间】:2012-02-26 00:13:29
【问题描述】:

例如,在 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开发者网页上,有一个good document关于如何使用fragment以及如何与activity进行通信,但是没有关于如何将数据从一个fragment传输到另一个fragment的描述......

【问题讨论】:

标签: android android-layout android-emulator android-intent


【解决方案1】:

使用

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

【讨论】:

  • 你的意思是我不需要在片段中定义接口并让主机活动实现在片段和主机活动之间建立通信的接口......相反,我可以使用你的代码来直接导航到下一个片段?
  • @its not blank 你能否详细说明 .navigateTo(fragment); android studio 似乎不认识这个
  • 导航到是我的本地方法。
【解决方案2】:

您从 Activity 发送数据的意图如下:

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

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多