我正在嘗試與活動中的片段進行交談,但我不確定片段是否可見或不存在。如果片段不存在,我甚至不能執行空檢查,因爲它會拋出異常。如何檢查片段是否存在?
如何檢查片段是否存在?
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();
}
如果這不起作用,發佈堆棧跟蹤,但您收到異常。
爲我完美工作..謝謝.. !! – OAEI 2014-06-07 09:22:48
鑄造null
來一個引用不會拋出異常,到一個原語,它會。
使用findFragmentById()
或findFragmentByTag()
得到一個參考,並檢查是否爲空,如果不是,檢查參考的isAdded()
或isVisible()
。
PlayerFragment p = (PlayerFragment) mManager.findFragmentById(R.id.bottom_container);
if(p != null && p.isAdded()){
p.onNotificationListener.updateUI();
}
關於'cast null'的好處 – 2017-01-31 06:53:58
難道你不能做空檢查,只有在那之後做鑄造? – 2013-02-23 15:16:26
我試過了。轉換後的對象不包含需要的元素。 – 2013-02-23 15:19:18
你有沒有在你的活動的XML文件中加入這個framgent – twocity 2013-02-23 16:47:12