将从MainActivity创建的对象发送到Fragments TabbedView

时间:2018-01-24 09:57:15

标签: java android android-fragments bluetooth

在我的App中,我开始使用带有MainActivity的TabbedView,每次都显示3个片段(取决于用户选择的内容)。

MainActivity.java启动蓝牙通信与OBD汽车和请求命令,直到应用程序打开。 现在,当OBD在我的MainActivity中响应时,我有一个处理响应的处理程序,并且使用setter()方法将此方法放在类PidsCommand.java中。

之后,我会将包含所有更新数据的Object包含在Fragment中,以实时显示数据。 因此,我需要在创建DashboardFragment并显示...

时传递此对象

有一些最好的方法吗?我的方式正确吗? 我如何将MainActivity中创建的Object共享给Fragment,以便我可以使用getter()方法获取数据并使用该数据弹出视图?

修改

我可以看到我只需要在创建一个新的碎片片段时传递该对象...不需要接口,因为我需要在创建片段时发送对象以读取它并显示数据。 / p>

这是Framgent的基准:

 public static DashboardFragment newInstance(OBDPids pids) {
        DashboardFragment dashboardfragment = new DashboardFragment();

        Bundle argsPids = new Bundle();
        argsPids.putBundle("pids", pids);
        dashboardfragment.setArguments(argsPids);

        return dashboardfragment;
    }

但putBundle和putParcable非常好....我怎样才能通过实例传递我的观点?

在片段中,我将数据带回:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_dashboard, container, false);

    Bundle args = getArguments();
    OBDPids pids = args.getParcelable("pids");

    return view;
}

或者这不是一个很好的方法吗?

编辑2

这个解决方案可以很好而不是界面吗?

在MainActivity.java中

pids = new OBDPids();
public OBDPids getMyObject() {
        return pids;
    }

在片段中

OBDPids myObjectFromActivity = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);

        MainActivity activity = (MainActivity) getActivity();
        myObjectFromActivity = activity.getMyObject();
return view;
}

0 个答案:

没有答案