2013-02-23 113 views
15

我正在尝试与活动中的片段进行交谈,但我不确定片段是否可见或不存在。如果片段不存在,我甚至不能执行空检查,因为它会抛出异常。如何检查片段是否存在?

如何检查片段是否存在?

PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container); 
playerFragment.onNotificationListener.updateUI(); 
+0

难道你不能做空检查,只有在那之后做铸造? – 2013-02-23 15:16:26

+0

我试过了。转换后的对象不包含需要的元素。 – 2013-02-23 15:19:18

+0

你有没有在你的活动的XML文件中加入这个framgent – twocity 2013-02-23 16:47:12

回答

26

一开始不要施放它。

Fragment f = mManager.findFragmentById(R.id.bottom_container); 
if(f != null && f instanceof PlayerFragment) { 
    PlayerFragment playerFragment = (PlayerFragment) f; 
    playerFragment.onNotificationListener.updateUI(); 
} 

如果这不起作用,发布堆栈跟踪,但您收到异常。

+0

为我完美工作..谢谢.. !! – OAEI 2014-06-07 09:22:48

10

铸造null来一个引用不会抛出异常,到一个原语,它会。

使用findFragmentById()findFragmentByTag()得到一个参考,并检查是否为空,如果不是,检查参考的isAdded()isVisible()

PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container); 
if(p != null && p.isAdded()){ 
    p.onNotificationListener.updateUI(); 
} 
+0

关于'cast null'的好处 – 2017-01-31 06:53:58