将数据从 Fragment Activity 传输到 Fragment [英] Transfer data from Fragment Activity to Fragment

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

问题描述

我正在我的应用程序中使用蓝牙服务,它使我能够从另一台设备接收到消息.在我的 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:

片段活动:

  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 但它不起作用..

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

我试过的代码:

在片段活动中:

    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 中获取我的数据.

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

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

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

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

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