Android: getSupporteFragment returns 空

Android: getSupporteFragment returns null

我的 Log.d 总是出现空指针异常。我不明白为什么 fragmendt 在上面创建时为 null。

name = "dashboard";
fragment = new FragmentDashboard();

final FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment, name);
transaction.addToBackStack(null);
transaction.commit();

FragmentDashboard fragmendt = (FragmentDashboard) activity.getSupportFragmentManager().findFragmentByTag("dashboard");
Log.d("DEBEUG", "test: " + fragmendt.toString());

FragmentTransaction#commit() 的描述为:"Schedules a commit of this transaction."。这意味着该片段会在未来的某个时间添加,但未定义何时添加。之后直接找碎片,交易还没发生

如果你想强制它立即创建和添加片段,可以使用同步工作的 FragmentTransaction#commitNow() 方法。请注意,您不能同时使用 addToBackstack(...)commitNow() 查看说明:

Transactions committed in this way may not be added to the FragmentManager's back stack, as doing so would break other expected ordering guarantees for other asynchronously committed transactions. This method will throw IllegalStateException if the transaction previously requested to be added to the back stack with addToBackStack(String).