我已经设置了一个列表,当我触摸列表中的一个项目时,我希望该应用程序生成一个AlertDialog。但是,当我触摸一个项目时,应用程序崩溃,我现在知道为什么。这是我的代码。
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 :(得分:0)
使用show
调用它。无需致电onCreateDialog
fragment.show(getFragmentManager(), "Some tag");
答案 1 :(得分:0)
您正在使用DialogFragment,因此您应该调用fragment.show()而不是onCreateDialog方法。