简体   繁体   中英

getting null value when passing value from activity to fragment?

How do i pass a value from an Activity to a Fragment ?

I understand that i can use setArgument in my Activity and getArgument in Fragment . But i did it with no luck. The value still returns as null.


Activity

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);

            }
        };

}

Fragment

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中可用。

Have you tried using a Tag to identify your Fragment and findFragmentByTag to retrieve it? It seems to me cleaner than using findFragmentById which actually look for the id of the inflated XML layout or the id of the container layout!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM