Android 如何检查片段是否存在?
我试图与活动中的片段对话,但我不确定该片段是否可见。如果该片段不存在,我甚至无法执行null检查,因为它会由于强制转换而引发异常 如何检查片段是否存在Android 如何检查片段是否存在?,android,android-fragments,Android,Android Fragments,我试图与活动中的片段对话,但我不确定该片段是否可见。如果该片段不存在,我甚至无法执行null检查,因为它会由于强制转换而引发异常 如何检查片段是否存在 PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container); playerFragment.onNotificationListener.updateUI(); 一开始不要投 Fragment f = mManager.findFragme
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();
}
如果这不起作用,请在收到异常的情况下发布stacktrace。将
null
强制转换到引用不会引发异常,而会引发原语异常
使用findFragmentById()
或findFragmentByTag()
获取引用并检查其是否为空,如果不是空,请检查引用的isAdded()
或isVisible()
你不能做空检查,然后再做施法吗?我试过了。强制转换后,对象不包含所需的元素。是否已将此框架添加到活动的xml文件中
PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if( p != null && p.isAdded()){
p.onNotificationListener.updateUI();
}