从捆绑中获取参数 [英] Getting arguments from a bundle
本文介绍了从捆绑中获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将Activity中的参数传递给Fragment,而我正在使用以下代码:
I'm trying to pass arguments from my Activity to a Fragment and I'm using this code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
String message = getIntent().getStringExtra(Intent.EXTRA_TEXT);
DetailActivityFragment fragment = new DetailActivityFragment();
Bundle bundle = new Bundle();
bundle.putString(INTENT_EXTRA, message);
fragment.setArguments(bundle);
}
我正在通过Intent Extra获取message变量的值,到目前为止,它仍然可以正常工作.
然后,我将其作为参数传递给片段,但是当我从该特定片段调用getArguments()
时,它将返回一个空Bundle.
有人对此有解决方案吗?
I'm getting the value of the message variable through an Intent Extra and that works fine, so far.
Then I'm passing it as an argument to my fragment but then, when I call getArguments()
from that specific Fragment it returns a null Bundle.
Does anybody have a solution to this?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null && bundle.containsKey(DetailActivity.INTENT_EXTRA)) {
forecast = bundle.getString(DetailActivity.INTENT_EXTRA);
} else if (bundle == null) {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_LONG).show();
}
}
当我运行应用程序时,上部方法显示一条Toast消息错误" ...
The upper method displays a Toast message "Error" when I run the app...
推荐答案
这是正确的方法
发送(在活动中):
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
final DetailActivityFragment frg = new DetailActivityFragment ();
ft.replace(R.id.container, frg);
final Bundle bdl = new Bundle();
bdl.putString("yourKey", "Some Value");
frg.setArguments(bdl);
ft.commit();
接收(在片段中):
final Bundle bdl = getArguments();
String str = "";
try
{
str = bdl.getString("yourKey");
}
catch(final Exception e)
{
// Do nothing
}
这篇关于从捆绑中获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文