android – 从包中获取参数

我正在尝试将我的Activity中的参数传递给片段,我正在使用此代码:

@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得到了消息变量的值,到目前为止工作正常.
然后我将它作为参数传递给我的片段然后,当我从该特定片段调用getArguments()时,它返回一个null Bundle.
有人有解决方案吗?

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

    }

当我运行应用程序时,upper方法显示Toast消息“Error”…

最佳答案
这是一种正确的方法

发送(在活动中):

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
}

转载注明原文:android – 从包中获取参数 - 代码日志