我對Fragment.isVisible()應該如何工作感到困惑。即使在Activity.create()
中添加了片段,即使使用FragmentManager.commitNow()
,Fragment.isVisible()
也會返回false。Fragment.isVisible()即使在添加了片段並且可見時也會返回false
Fragment.isVisible()
即使在onResume()
中也返回錯誤。但是,當點擊一個UI按鈕時,返回的值是正確的。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public final static String TAG = "HideFragmentOnChange";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button)findViewById(R.id.my_button)).setOnClickListener(this);
if(savedInstanceState == null){
Fragment fragmentA = new FragmentA();
Log.d(TAG, "onCreate: Before FragmentTransaction FragA: " + (fragmentA.isVisible() ? "visible" : "not visible"));
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragmentA, "fragA")
.commitNow();
Log.d(TAG, "onCreate: After FragmentTransaction FragA: " + (fragmentA.isVisible() ? "visible" : "not visible"));
}
this.runOnUiThread(new Runnable(){
@Override
public void run() {
Fragment fragA = getSupportFragmentManager().findFragmentByTag("fragA");
Log.d(TAG, "runOnUiThread after onCreate(): FragA: " + (fragA.isVisible() ? "visible" : "not visible"));
}
});
}
@Override
protected void onResume() {
super.onResume();
Fragment fragA = getSupportFragmentManager().findFragmentByTag("fragA");
Log.d(TAG, "onResume: FragA: " + (fragA.isVisible() ? "visible" : "not visible"));
this.runOnUiThread(new Runnable(){
@Override
public void run() {
Fragment fragA = getSupportFragmentManager().findFragmentByTag("fragA");
Log.d(TAG, "runOnUiThread after onResume(): FragA: " + (fragA.isVisible() ? "visible" : "not visible"));
}
});
}
@Override
public void onClick(View v) {
Fragment fragmentA = getSupportFragmentManager().findFragmentByTag("fragA");
Log.d(TAG, "onClick(): FragA: " + (fragmentA.isVisible() ? "visible" : "not visible"));
}
}
我最初以爲也許是因爲主線程一直沒有尚未運行的機會和FragmentTransaction
不充分和適當地提交到以後的點。但是,撥打runOnUiThread
不會更改返回值isVisible()
。
我附上日誌以供參考。
03-15 17:22:34.978 14094-14094/ D/HideFragmentOnChange: onCreate: Before FragmentTransaction FragA: not visible
03-15 17:22:34.990 14094-14094/ D/HideFragmentOnChange: onCreate: After FragmentTransaction FragA: not visible
03-15 17:22:34.991 14094-14094/ D/HideFragmentOnChange: runOnUiThread after onCreate(): FragA: not visible
03-15 17:22:34.996 14094-14094/ D/HideFragmentOnChange: onResume: FragA: not visible
03-15 17:22:34.996 14094-14094/ D/HideFragmentOnChange: runOnUiThread after onResume(): FragA: not visible
03-15 17:22:56.683 14094-14094/ D/HideFragmentOnChange: onClick(): FragA: visible
爲什麼Fragment.isVisible()
似乎有這麼大的延遲返回正確的值?
我正在使用支持庫25.2並支持庫碎片,儘管本機碎片產生了相同的行爲。
這個工作,非常感謝!!!!!! –