[英]Send data from Activity to Fragment already created
我只找到了有关如何创建片段向其发送一些数据的信息,但仅在其与构造函数的实例化中。
但我想知道是否可以从Activity中将一些数据(例如,两个Double对象)发送到Fragment,而无需创建Fragment的新实例。
先前已创建的片段。
最简单的方法是在Fragment中定义一个接口并在活动中实现它。 此链接应提供有关如何完成此操作的详细示例。 https://developer.android.com/training/basics/fragments/communicating.html
我认为你要找的关键部分在这里:
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,则可以调用您在接口中定义的方法向其发送一些数据。
您可以通过以下捆绑包传输任何数据:
Bundle bundle = new Bundle();
bundle.putInt(key, value);
your_fragment.setArguments(bundle);
然后在你的Fragment中,检索数据(例如在onCreate()方法中):
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt(key, defaultValue);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.