从片段活动数据传输到分片 [英] Transfer data from Fragment Activity to Fragment

查看:195
本文介绍了从片段活动数据传输到分片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与我的应用程序中的蓝牙服务,ABLES我得到从其他设备接收到的消息。在我FragmentActivity,我使用一个处理程序来获取这样的信息:

I'm working with a bluetooth service in my application which ables me to get received message from another device. In my FragmentActivity, i'm using a handler to get this message:

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..
              }
        }
  }

从该处理程序,我想获得的数据并将其传送到一个​​片段。 我试图用包,但它不能正常工作。

From this Handler I would like to get a data and transfer it to a Fragment. I tried to use bundle but it doesn't work..

在code我想:

在FragmentActivity:

In 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();
}

应用程序将返回普劳特,这意味着它不能从我的FragmentActivity得到我的数据。

The application is returning "prout" which means that it can't get my data from my FragmentActivity.

是否有任何其他的方式来获得数据弗罗姆一个fragmentActivity并将其传送到一个​​片段?

Is there any other way to get a data frome a fragmentActivity and transfer it to a fragment?

感谢您的帮助

推荐答案

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

Assuming that you need pass the data to the fragment at creation time, you could use setArguments() to pass data to the fragment, and getArguments() to read that data.

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);

但是,如果已经创建了片段,那么你可以创建一个你会用它来传递数据的片段里面的方法,是这样的:

But if the fragment is already created, then you could create a method inside the fragment that you'll use to pass data, something like this:

fragment.setBattery(bat);

这篇关于从片段活动数据传输到分片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆