0

我正在使用ActionBar Tabs. Android 4我有 5 个Broadcast receivers,它们都更新了 UI 的一部分。我的应用程序中有两个选项卡,两个选项卡都有不同的 UI 关联(即两个选项卡都有不同的 xml 文件与之关联,这些文件将根据选项卡选择进行膨胀)。对于每个选项卡,我都在膨胀一个片段。

最初,我只显示一个选项卡。单击与该选项卡关联的 UI 中的按钮时,我添加了另一个选项卡,并收到 5 个广播接收器。我以任何顺序获得广播接收器。现在说有以下广播接收器:A B C D E

A, B, D and E updates the UI which is part of Tab 1.   

C updates the UI which is part of Tab 2.

每当创建一个新选项卡时,它的 UI 都会被前一个选项卡的 UI 替换,所以当比如说A and B被调用时,它们会更新来自 Tab 1 的 UI,但是当收到 C 时,UI 现在会替换为 Tab2 的 UI,并且它更新 UI,但是当D and E收到时,他们尝试更新选项卡 1 的 UI,但由于选项卡 2 现在已膨胀,我在D and E尝试进行更改的语句上出现空指针异常。

所以请告诉我,我应该如何根据广播公司更新我的 UI?

更新:现在,我在以下方面得到了 NPE:这是在我的一个接收器内,在这里我正在创建新选项卡并希望从广播接收器中插入一个表。

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

final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mdsTable); // NPE linearLayout is not getting initialized.

我不明白为什么会这样,因为我已将 MyTabsListener 实现为:

class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;

    public MyTabsListener(Fragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        Toast.makeText(StartActivity.appContext, "Reselected!",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
    }
}
4

1 回答 1

0

我在这里所做的是,首先,每当我收到时Broadcast Receivers,我不会在onReceive()方法中更新 UI,而是将收到的数据保存到持久存储中。

并且根据事件,我曾经创建一个新的选项卡。现在,当用户导航到新选项卡时,onCreateView()会为该选项卡调用 ,然后我在此方法中更新 UI。

所以没有问题:

Whenever a new tab is created, its UI gets replaced with previous tab's UI, so when, say A and B gets called, they update the UI which is from Tab 1, but when C is received, the UI is now replaced with Tab2's UI, and it updates the UI, but when D and E is received, they try to update the UI of tab 1, but since tab 2 is now inflated, I get null pointer exception on that statement on which D and E tried to make change.

onCreateView()因为我在每个选项卡的每个方法中更新了 UI 。

于 2012-08-06T13:58:04.373 回答