我知道有这个文件
http://developer.android.com/reference/android/app/DialogFragment.html#AlertDialog
但是作为一个新的Android / Java学习者,通过编写一个简单的警报对话框可以看到2个选项(是/否)消息弹出的代码量并不容易.
final private int RESET_DIALOG = 0; private OnClickListener resetButtonListener = new OnClickListener() { @Override public void onClick(View v) { showDialog(RESET_DIALOG); } }; protected android.app.Dialog onCreateDialog(int id) { switch(id) { case RESET_DIALOG: AlertDialog.Builder builder = new Builder(this); return builder .setMessage("Are you sure you want to reset the count?") .setNegativeButton("No",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0,int arg1) { Toast.makeText(MainActivity.this,"Did not reset!",5).show(); } }) .setPositiveButton("Yes",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0,"Did Reset!",5).show(); } }) .create(); } return null; };
这是我尝试按照Android网站上的说明进行操作:主要活动文件:
final private int RESET_DIALOG = 0; private OnClickListener resetButtonListener = new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,MainDialog.class); startActivity(intent); } }; protected android.app.Dialog onCreateDialog(int id) { switch(id) { case RESET_DIALOG: AlertDialog.Builder builder = new Builder(this); return builder .setMessage("Are you sure you want to reset the count?") .setNegativeButton("No",5).show(); } }) .create(); } return null; };
然后创建一个MainDialog类:(我实际上失去了如何正确地做这个或应用它)
package com.proteintracker; import android.support.v4.app.DialogFragment; public class MainDialog extends DialogFragment { public static MyAlertDialogFragment newInstance(int title) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putInt("title",title); frag.setArguments(args); return frag; } }
我不知道我是否假设为片段创建一个新类,以及如何将它应用到活动屏幕中的当前对话框中.
解决方法
您可以像这样显示您的DialogFragment:
void showDialog() { DialogFragment newFragment = MyAlertDialogFragment.newInstance( R.string.alert_dialog_two_buttons_title); newFragment.show(getFragmentManager(),"dialog"); }
在片段对话框中,您应该覆盖onCreateDialog并返回简单对话框的实例,例如AlertDialog.
public static class MyAlertDialogFragment extends DialogFragment { public static MyAlertDialogFragment newInstance(int title) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putInt("title",title); frag.setArguments(args); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { int title = getArguments().getInt("title"); AlertDialog.Builder builder = new Builder(this); return builder .setMessage("Are you sure you want to reset the count?") .setNegativeButton("No",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0,int arg1) { Toast.makeText(MainActivity.this,5).show(); } }) .setPositiveButton("Yes",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0,5).show(); } }) .create(); } }