首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数据从活动发送到已创建的片段

问将数据从活动发送到已创建的片段
EN

Stack Overflow用户
提问于 2017-07-07 07:33:51
回答 3查看 15.1K关注 0票数 13

我只找到了关于如何创建一个向其发送一些数据的片段的信息,但仅在它与构造函数的实例化过程中。

但我想知道是否有可能将一些数据(例如,两个双对象)从活动发送到片段,而不必创建片段的新实例。

先前创建的片段。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-07 09:59:46

只需在片段中添加一个要接收参数的方法,然后在Activity中调用该方法。

活动代码:

​

片段的代码:

​

​

票数 16
EN

Stack Overflow用户

发布于 2017-07-07 07:42:44

您可以通过如下捆绑包传输任何数据:

代码语言:javascript
复制
Bundle bundle = new Bundle();
bundle.putInt(key, value);
your_fragment.setArguments(bundle);

然后在您的片段中,使用以下命令检索数据(例如,在onCreate()方法中):

代码语言:javascript
复制
Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}
票数 3
EN

Stack Overflow用户

发布于 2017-07-07 07:40:00

最简单的方法是在片段中定义一个接口,并在活动中实现它。此链接应提供有关如何实现此目标的详细示例。https://developer.android.com/training/basics/fragments/communicating.html

我认为你正在寻找的关键部分在这里:

代码语言:javascript
复制
ArticleFragment articleFrag = (ArticleFragment)
      getSupportFragmentManager().findFragmentById(R.id.article_fragment);

if (articleFrag != null) {
    // If article frag is available, we're in two-pane layout...

    // Call a method in the ArticleFragment to update its content
    articleFrag.updateArticleView(position);
} else {
    // Otherwise, we're in the one-pane layout and must swap frags...

    // Create fragment and give it an argument for the selected article
    ArticleFragment newFragment = new ArticleFragment();
    Bundle args = new Bundle();
    args.putInt(ArticleFragment.ARG_POSITION, position);
    newFragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

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

    // Commit the transaction
    transaction.commit();
}

首先,尝试通过调用findFragmentById(R.id.fragment_id)来检索片段,如果它不是null,则可以调用在接口中定义的方法来向其发送一些数据。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44960380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档