如何检查片段是否存在?

Art*_*ans 15 android android-fragments

我试图与活动中的片段进行对话,但我不确定片段是否可见.如果片段不存在,我甚至不能进行null检查,因为它会因为强制转换而抛出异常.

如何检查片段是否存在?

PlayerFragment = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
playerFragment.onNotificationListener.updateUI();
Run Code Online (Sandbox Code Playgroud)

Fly*_*n81 30

一开始不要施放它.

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

如果在使用您收到的异常的堆栈跟踪后不起作用.


S.D*_*.D. 11

转换null为引用不会将异常抛出到原语,它会.

使用findFragmentById()findFragmentByTag()获取引用并检查其是否为null,如果不是,则检查引用isAdded()isVisible().

PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if( p != null && p.isAdded()){
   p.onNotificationListener.updateUI();
}
Run Code Online (Sandbox Code Playgroud)