2013-05-09 206 views
0

我創建了一個AlertDialogFragment類,我試圖用下面的代碼從另一個類中顯示它,但我不斷收到一個錯誤,將類型從FragmentTranscation更改爲FragmentManager。如果我將其更改爲FragmentManager,我得到一個消息更改爲FragmentTranscation,每當我改變FragmentTranscation,我得到一個消息更改爲FragmentManager:對話框不會顯示

這裏是展示alertDialog代碼:

FragmentTransaction ft= getFragmentManager().beginTransaction(); 
AlertDialogFragment newFragment= new AlertDialogFragment(); 
newFragment.show(ft, "alertDialog"); 

下面是類代碼:

public class AlertDialogFragment extends android.support.v4.app.DialogFragment { 
@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    AlertDialog.Builder builder 
    = new AlertDialog.Builder(getActivity()); 
    builder.setMessage("Staying in Touch With The Ones You Love"); 
    builder.setTitle("Togetherness"); 
    builder.setCancelable(false); 
    builder.setPositiveButton("yes", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 

     } 
    }); 
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 

     } 
    }); 
    return builder.create(); 
} 
} 
+0

檢查本教程 - > http://vinaygopinath.wordpress.com/2012/11/10/alertdialog-using-fragment/ – 2013-05-09 06:59:58

回答

0

要顯示片段,您需要替換現有的片段或將新的片段添加到現有的視圖。

編輯:對不起,沒有注意到它是一個對話框片段。 使用此:

// DialogFragment.show() will take care of adding the fragment 
// in a transaction. We also want to remove any currently showing 
// dialog, so make our own transaction and take care of that here. 
FragmentTransaction ft = getFragmentManager().beginTransaction(); 
Fragment prev = getFragmentManager().findFragmentByTag("alertDialog"); 
if (prev != null) { 
    ft.remove(prev); 
} 
ft.addToBackStack(null); 

// Create and show the dialog. 
newFragment.show(ft, "alertDialog"); 

這裏看看例子:http://developer.android.com/reference/android/app/DialogFragment.html

記住如果你使用的是老式API級別片段API等級11介紹,按照說明這裏使用支持庫的所有片段的東西(我看你DialogFragment已經從支持庫FragmentDialog繼承)

http://developer.android.com/training/basics/fragments/support-lib.html

+0

非常感謝。這工作完美! – user2348040 2013-05-10 00:36:05

+0

這正是我所期待的。 – user2348040 2013-05-10 00:41:30

0

嘗試使用

FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
+0

非常感謝。這工作完美! – user2348040 2013-05-10 00:34:54

+0

請將此標記爲準確答案:) – Neoh 2013-05-10 13:53:47