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

时间:2012-07-31 17:14:15

标签: android android-activity fragment

如何将值从Activity传递到Fragment

我了解我可以setArgument使用ActivitygetArgument使用Fragment。但我这样做没有运气。该值仍然返回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);
  }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您是否尝试使用标记来识别Fragment并使用findFragmentByTag来检索它? 在我看来比使用findFragmentById更清晰,它实际上是在寻找膨胀的XML布局的id或容器布局的id!

相关问题