Android 将值从活动传递到片段时获取空值?

Android 将值从活动传递到片段时获取空值?,android,android-activity,fragment,Android,Android Activity,Fragment,如何将值从活动传递到片段 我知道我可以在我的活动中使用setArgument,在Fragment中使用getArgument。但是我没有运气。该值仍然返回为null 活动 public class nfc_activity extends Activity { private ImageView mCardView; MyFragmentA f2; public static String itemname; protected void onCreate(B

如何将值从
活动
传递到
片段

我知道我可以在我的
活动中使用
setArgument
,在
Fragment
中使用
getArgument
。但是我没有运气。该值仍然返回为null


活动

public class nfc_activity extends Activity {
    private ImageView mCardView;
    MyFragmentA f2;
    public static String itemname;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         Button goButton = (Button)findViewById(R.id.go);
            goButton.setOnClickListener(mGoListener);


        }

       private OnClickListener mGoListener = new OnClickListener()
        {
            public void onClick(View v)
            {
                // Here we start up the main entry point of our redirection
                // example.
                String itemname ="1";

                  MyFragmentA fragment = new MyFragmentA();
                Bundle bundle2 = new Bundle();
                bundle2.putString("key", itemname);
                fragment.setArguments(bundle2);

            }
        };

}

碎片

public class MyFragmentA extends Fragment {



 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {

  Bundle bundle = this.getArguments();
  if (bundle != null) {
      String hello = bundle.getString("key", defaultValue);
      System.out.println(hello);
  }

您的代码没有显示您的片段是如何附加到活动的,但在附加片段之前,您必须确保已在片段上设置参数,以便它们在onCreateView中可用。

您是否尝试过使用标记来标识您的片段并使用findFragmentByTag来检索它?
在我看来,这似乎比使用findFragmentById更干净,findFragmentById实际上查找膨胀XML布局的id或容器布局的id

可能与您提到的API级别重复?类似于:Fragment Fragment=(Fragment)getFragmentManager().findFragmentById(R.id.pager);Bundle bundle2=新Bundle();bundle2.putString(“key”,itemname);fragment.setArguments(bundle2);我用这个得到了nullpointerexception。请帮忙