2016-03-07 35 views
0

UPDATE: 只是爲了澄清,show()android.app.DialogFragment的方法,我沒有改寫:findFragmentByTag()返回null

public void show(FragmentManager manager, String tag) { 
    mDismissed = false; 
    mShownByMe = true; 
    FragmentTransaction ft = manager.beginTransaction(); 
    ft.add(this, tag); 
    ft.commit(); 
} 

我們稱以下,其中MyDialog擴展DialogFragment

MyDialog dialog = new MyDialog(); 
    dialog.show(getFragmentManager(), MyDialog.TAG); 

    Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG); 

但是f總是null。爲什麼?

+0

您是否設置了具有相同標記的片段? –

+1

請在MyDialog類的show()方法上發佈代碼。 –

+0

@AritraRoy補充。 – shebang

回答

0

FindFragmentByTag如果找到則返回片段,否則返回null。

+0

當然。問題是爲什麼找不到最近添加的片段。 – shebang

+0

@shebang你應該添加你的整個代碼 – dnkilic

0

添加標籤與片段

Fragment fragmentA = new FragmentA(); 
getFragmentManager().beginTransaction() 
    .replace(R.id.container,f,MyDialog.TAG) 
    .commit(); 

,並獲得

Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG); 
+0

你能解釋這與show()有什麼不同嗎?也就是說,replace()比'add()'更好' – shebang

+0

請訪問http://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack –

0

問題很簡單,DialogFragment.show使用FragmentTransaction.commit其異步運行。所以它只會顯示在主線程的下一個迭代中。要解決這個問題,只需將這一行添加到您的代碼中...

MyDialog dialog = new MyDialog(); 
dialog.show(getFragmentManager(), MyDialog.TAG); 

// Run this line before trying to search for the fragment. 
getFragmentManager().executePendingTransactions(); 

Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);