2012-06-11 26 views
0

我在Android 4中使用ActionBar Tabs。我有5 Broadcast receivers,並且他們都更新了UI的一部分。在我的應用程序中有兩個選項卡,兩個選項卡都有不同的UI關聯(即,兩個選項卡都有不同的xml文件關聯,這些文件將根據選項卡進行充填)。對於每個選項卡,我正在對一個片段進行膨脹使用廣播接收器和標籤在ActionBar中開發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. 

每當創建一個新的標籤,其用戶界面得到與前一個標籤的用戶界面所取代,所以當,說A and B被調用,它們將更新其是由表1中的UI,但是當收到C時,用戶界面現在替換爲Tab2的用戶界面,並更新UI,但是當收到D and E時,他們嘗試更新標籤1的UI,但由於標籤2現在被誇大了,我得到空指針異常在那個D and E試圖改變的聲明上。

所以請告訴我,我應該如何根據廣播公司更新我的用戶界面?

更新:現在,我得到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); 
    } 
} 
+0

如果你現在可以分享你在這個問題上找到的解決方案,那將是非常好的。 – Flexo

回答

0

這裏我所做的是,首先,每當我收到Broadcast Receivers,我不更新onReceive()方法中的用戶界面,而不是用於將我收到的數據保存到持久性存儲中。

基於事件,我用來創建一個新的Tab。現在,當用戶導航到新標籤頁時,該標籤將調用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。