我正在主要活动中动态地在容器中添加一个片段。我希望在以后使用片段实例,但片段管理器始终返回null。我在做什么错了?
我已经尝试了多次。可以通过运行该应用程序来添加片段,但我找不到它们。
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: Starting OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.list_frag_cont, new ListFrag(),"listfrag").commit();
getSupportFragmentManager().beginTransaction().add(R.id.detail_frag_cont, new DetailFrag(),"detailfrag").commit();
ListFrag listFrag=(ListFrag)getSupportFragmentManager().findFragmentByTag("listfrag");
DetailFrag detailFrag=(DetailFrag)getSupportFragmentManager().findFragmentByTag("detailfrag");
if(listFrag==null)
Log.d(TAG, "onCreate: listFrag is null");
if(detailFrag==null)
Log.d(TAG, "onCreate: detailFrag is null");
Log.d(TAG, "onCreate: Exitting OnCreate");
期望的日志应该是
2019-07-07 16:59:57.098 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: Starting OnCreate
2019-07-07 16:59:57.224 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: Exitting OnCreate
但这是我得到的日志
2019-07-07 16:59:57.098 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: Starting OnCreate
2019-07-07 16:59:57.224 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: listFrag is null
2019-07-07 16:59:57.224 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: detailFrag is null
2019-07-07 16:59:57.224 10087-10087/com.kinshuu.silverbook D/MyLOGS: onCreate: Exitting OnCreate
答案 0 :(得分:0)
好吧,我得到了答案,这是因为交易没有立即提交。为此,您需要使用fragmentmanager。执行更改。