使用片段标签检索片段

Retrieving Fragment by using Fragment Tag

当通过 SupportFragmentManager 添加期间定义的标签检索 Fragment 时,我得到 NullPointerException

代码如下:

 FragmentOne fragmentOne = new FragmentOne();
    getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentOne,FRAGMENT_ONE_TAG).addToBackStack(null).commit();

    FragmentOne fragmentOneInstance = (FragmentOne) getSupportFragmentManager().findFragmentByTag(FRAGMENT_ONE_TAG);
    Log.i("Fragment One Instance: ", fragmentOneInstance.getTag());

错误报告:

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.demo.fragment/com.ms.android.demo.fragment.MainActivity}: java.lang.NullPointerException

您必须等到交易执行完毕。在将片段添加到交易后,您不能立即 运行 它。

.commit(); 是一个异步调用。

来自文档

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

作为测试,您可以运行 executePendingTransactions () 立即执行任何挂起的操作。

片段交易是异步任务,当您提交时,并不意味着它会立即添加,因此如果您希望交易立即发生,您必须调用 executePendingTransactions()

FragmentOne fragmentOne = new FragmentOne();
    getSupportFragmentManager().beginTransaction().add(R.id.container, fragmentOne,FRAGMENT_ONE_TAG).addToBackStack(null).commit();

getSupportFragmentManager().executePendingTransactions();