簡體   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