这是我的代码,我评论了我需要的东西。我尝试了一些代码,但似乎与Fragment不兼容。
public class main extends Fragment {
ImageButton imagebutton;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main, container, false);
imagebutton = (ImageButton) rootView.findViewById(R.id.im);
imagebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Open Yes/No Dialog
//if Yes do something
}
});
}
}
答案 0 :(得分:19)
试试这个方法:
private void createAndShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("My Title");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//TODO
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//TODO
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
答案 1 :(得分:1)
class MyDialogFragment extends DialogFragment{
Context mContext;
public MyDialogFragment() {
mContext = getActivity();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Really?");
alertDialogBuilder.setMessage("Are you sure?");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "CLick-Click!!",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
创建对话框调用:
new MyDialogFragment().show(getFragmentManager(), "MyDialog");
并从某处解雇对话:
((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss();
要么
尝试使用此代码段:
AlertDialog.Builder mDialog = new AlertDialog.Builder(MyClassNane.this);
mDialog.setTitle("Title");
mDialog.setMessage("Do you want to delete ?");
mDialog.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Toast.makeText(getApplicationContext(),
"Click-Click!!",Toast.LENGTH_LONG).show();
}
dialog.cancel();
}
});
mDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = mDialog.create();
alert.show();