将数据从Fragment Activity传输到Fragment

时间:2013-07-26 07:49:44

标签: android bundle fragment android-fragmentactivity

我正在使用我的应用程序中的蓝牙服务,这让我能够从另一台设备收到消息。在我的FragmentActivity中,我正在使用处理程序来获取此消息:

FragmentActivity:

  public final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                  //my code

                  case MESSAGE_READ:
                         byte[] readBuf = (byte[]) msg.obj;
                         byte[] alpha = null;
                         alpha=readBuf;

                         if(alpha!=null){
                          //my code..
              }
        }
  }

从这个Handler我想获得一个数据并将其传输到Fragment。 我试图使用bundle但它不起作用..

我试过的代码:

在FragmentActivity中:

    Intent intent = new Intent();
intent.setClass(getApplicationContext(), General.class);
Bundle bundle=new Bundle();
bundle.putInt("battery", bat);
intent.putExtra("android.intent.extra.INTENT", bundle);

在片段中:

Bundle bundle = getActivity().getIntent().getExtras();
if (bundle != null) {
int mLabel = bundle.getInt("battery", 0);
Toast.makeText(getActivity(), "tottiti: "+mLabel, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "prout", Toast.LENGTH_SHORT).show();
}

应用程序返回“prout”,这意味着它无法从FragmentActivity获取我的数据。

有没有其他方法可以将数据从fragmentActivity中获取并将其传输到片段?

感谢您的帮助

1 个答案:

答案 0 :(得分:4)

假设您需要在创建时将数据传递给片段,您可以使用setArguments()将数据传递给片段,并使用getArguments()来读取该数据。

Bundle bundle = new Bundle();
bundle.putInt("battery", bat);
MyFragment fragment=new MyFragment();
fragment.setArguments(bundle);

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_container,fragment);
ft.commit();

然后在片段的onCreate()方法中:

Bundle bundle=getArguments(); 
int mLabel = bundle.getInt("battery", 0);

但是如果已经创建了片段,那么你可以在片段中创建一个用于传递数据的方法,如下所示:

fragment.setBattery(bat);