0

如何将值从 a 传递Activity到 a Fragment

我知道我可以setArgument在 myActivitygetArgumentin 中使用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);
  }
4

2 回答 2

0

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

于 2012-08-19T01:49:26.010 回答
0

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

于 2012-07-31T18:07:25.713 回答