繁体   English   中英

从活动向片段传递值时得到空值?

[英]getting null value when passing value from activity to fragment?

如何将值从Activity传递给Fragment

我明白,我可以使用setArgument在我的ActivitygetArgumentFragment 但是我没有运气。 该值仍返回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中可用。

您是否尝试过使用Tag来识别您的Fragment并使用findFragmentByTag进行检索? 在我看来,比使用findFragmentById更干净,它实际上是查找膨胀的XML布局的ID或容器布局的ID!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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