2014-12-23 200 views
0

我設置了一個列表,當我觸摸列表中的一個項目時,我希望應用程序生成AlertDialog。但是,當我觸摸一個項目時,該應用程序崩潰,現在我想知道爲什麼。這是我的代碼。使用AlertDialogs時應用程序崩潰

DATA = new ArrayList<Student>(); 
    adapter1 = new StudentAdapter(this, R.layout.studentitemlayout, DATA); 
    listview01 = (ListView) findViewById(R.id.ListView01); 
    listview01.setAdapter(adapter1); 

    listview01.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      Log.i(DEBUG_TAG, "You clicked " + position + " student"); 
      AlertDialogFragment fragment = new AlertDialogFragment(); 
      fragment.onCreateDialog(savedInstanceState).show(); 
     } 
    }); 

和我的片段

public class AlertDialogFragment extends DialogFragment { 

private static final String DEBUG_TAG = "MyStudentsData"; 

public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the Builder class for convenient dialog construction 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setMessage("New Lesson!") 
      .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        Log.i(DEBUG_TAG , "YES"); 
       } 
      }) 
      .setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        Log.i(DEBUG_TAG , "NO"); 
       } 
      }); 
    // Create the AlertDialog object and return it 
    return builder.create(); 
} 

}

和最後一個問題 爲什麼這個代碼失敗,讓我崩潰的應用程序類?

/*newLessonAlertDialog fragment = new newLessonAlertDialog(); 
      fragment.show(getFragmentManager(),DEBUG_TAG); */ 
      AlertDialog alert = new AlertDialog.Builder(getApplicationContext()).create(); 
      alert.setTitle("nikos"); 
      alert.show(); 

回答

0

show打電話吧。無需調用onCreateDialog

fragment.show(getFragmentManager(), "Some tag"); 
+0

謝謝你爲我工作,但我不明白爲什麼。 當我生成一個片段如何調用onCreateDialog? – kaposnick

+0

它在片段內完成。閱讀文檔http://developer.android.com/reference/android/app/DialogFragment.html –

+0

@ user3596026接受答案怎麼樣?它幫助你了嗎? –

0

您使用DialogFragment,所以你應該叫fragment.show(),而不是onCreateDialog方法。