2014-12-23 161 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方法。