我正在尝试制作包含Activity
和两个Fragments
的应用。任何片段都可以调用由Activity
实现的接口方法:
@Override
public void onFragmentRequest(final String fragmentTag) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// simulate network connection
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Fragment fragment = getSupportFragmentManager()
.findFragmentByTag(fragmentTag);
if(fragment == null)
Log.d(TAG, "fragment is null");
else {
if(fragment instanceof OnFragmentResponse)
((OnFragmentResponse) fragment).onFragmentResponse();
}
}
});
}
}).start();
}
但问题是在致电onFragmentRequest
并使设备轮换getSupportFragmentManager().findFragmentByTag(fragmentTag)
后返回null
我替换所有片段并添加到后台堆栈,然后我调用commit
方法和manager.executePendingTransactions()
,但没有帮助
在轮换之前或之后记录:
02-07 16:39:12.202 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment
02-07 16:39:12.203 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1
02-07 16:39:12.203 29750-29750/com.testfrag3 D/NewsFragment: onFragmentResponse success
呼叫onFragmentRequest
和设备轮换时记录:
02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment
02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1
02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: fragment is null
答案 0 :(得分:0)
试试这个:
getSupportFragmentManager().executePendingTranscation();