片段和广播接收器

Shr*_*ant 6 android broadcastreceiver android-fragments

我有activity两个fragments.我没有使用<fragment/>标签,我有两个扩展的类Fragment,在那个片段中,我有:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.bfragment, container, false); // this will inflate the Fragment in activity.
    }
Run Code Online (Sandbox Code Playgroud)

现在的问题是,我正在接收一些活动中的广播接收器,其中一些接收器从第一个片段更新UI,一些接收器从第二个更新UI.

我主要活动中定义的一个广播接收器是:

private BroadcastReceiver bcReceived = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            Log.d("", "BC Object Received");

            ActionBar actionbar = getActionBar();
            actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            ActionBar.Tab bTab = actionbar.newTab().setText("B");
            Fragment fragment = new BFragment();
            bTab.setTabListener(new MyTabsListener(fragment));
            actionbar.addTab(bTab, true);

            final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.bTable);  // Getting null pointer exception here. linearLayout is not getting initialized.
Run Code Online (Sandbox Code Playgroud)

我想使用上面的linearLayout并使用它来夸大其中的视图.但是获得NPE.

在这里,当一些广播接收器更新第一个片段时,它可以正常工作,但是当广播接收器从活动中更新第二个片段时,我得到了NPE.

我的问题是:我应该如何以及在何处更新片段?它应该在我的活动中吗?如果是,那么在哪种方法?如果没有那么我应该在哪里更新片段?

请帮我!!!

Tim*_*nin 25

您的活动逻辑应与片段逻辑分开.

你的活动应该处理如下逻辑:

我需要显示这个片段而不是那个片段

但是你的活动应该处理这种逻辑:

我需要更新片段内的内容

片段的责任是更新它的内容.另一方面,活动可以告诉片段它需要更新自己.

考虑到这一点,你的片段应该暴露像这样的方法

updateContent(With Blabla)
Run Code Online (Sandbox Code Playgroud)

要么

updateContent()
Run Code Online (Sandbox Code Playgroud)

在您的活动中,当BroadcastReceiver收到您应该接受的内容时:

  • 检查当前显示的片段
  • 准备要在片段中更新的内容
  • 请求使用该updateContent(With Blabla)方法更新片段.

要么

  • 检查当前显示的片段
  • 请求片段使用该updateContent()方法更新自己.

根据您的应用程序业务逻辑选择最简单的方法.