【发布时间】:2012-06-12 08:17:04
【问题描述】:
我有一个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.
}
现在的问题是,我正在接收一些广播接收器,其中一些接收器从第一个片段更新 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.
我想使用上面的 linearLayout 并用它来膨胀其中的视图。但是得到 NPE。
在这里,当一些广播接收器更新第一个片段时,它可以正常工作,但是当广播接收器从活动更新第二个片段时,我得到 NPE。
我的问题是:我应该如何以及在哪里更新片段?它应该在我的活动中吗?如果是,那么用哪种方法?如果没有,那么我应该在哪里更新片段?
请帮帮我!!!
【问题讨论】:
-
两个片段的布局(R.layout.bfragment)是否相同? R.id.bTable 是否存在于两个片段中?
-
如果您询问两种布局是否相似,则否。但是通过替换之前的布局,两种布局都会在同一个容器中膨胀。
-
R.id.bTable 是你的容器吧?
-
没有。 bFragment 是我的容器。而 R.id.bTable 就是这个容器内的一个线性布局。
-
您可能会找到解决方案here。
标签: android broadcastreceiver android-fragments