我正在尝试从活动中与片段交谈,但我不确定片段是否可见。如果该片段不存在,我什至无法进行空检查,因为它会由于强制转换而引发异常。
如何检查片段是否存在?
PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
playerFragment.onNotificationListener.updateUI();
我正在尝试从活动中与片段交谈,但我不确定片段是否可见。如果该片段不存在,我什至无法进行空检查,因为它会由于强制转换而引发异常。
如何检查片段是否存在?
PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
playerFragment.onNotificationListener.updateUI();
一开始不要投。
Fragment f = mManager.findFragmentById(R.id.bottom_container);
if(f != null && f instanceof PlayerFragment) {
PlayerFragment playerFragment = (PlayerFragment) f;
playerFragment.onNotificationListener.updateUI();
}
如果这不起作用,则发布堆栈跟踪,并收到您收到的异常。
强制null
转换为引用不会抛出异常,但会抛出异常。
使用findFragmentById()
orfindFragmentByTag()
获取引用并检查其是否为空,如果不是,请检查引用的isAdded()
or isVisible()
。
PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if( p != null && p.isAdded()){
p.onNotificationListener.updateUI();
}