public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Button btn = findViewById(R.id.button1);
btn.setOnClickListener(v -> {
with();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
with();
});
}
public void with() {
FragmentManager fm = this.getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag("abc");
if (fragment == null) {
Log.i("hunter", "这一行执行了两次");
fragment = new Fragment();
fm.beginTransaction().add(fragment, "abc").commitAllowingStateLoss();
}
}
}
老师,上面的代码new Fragment()怎么执行了两次,第一次添加Fragment的时候设置了tag呀