final AlertDialog dialog = new AlertDialog.Builder(context).setView(v).setTitle(R.string.my_title).setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick.setNegativeButton(android.R.string.cancel, null).create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Overridepublic void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);button.setOnClickListener(new View.OnClickListener() {
@Overridepublic void onClick(View view) {// TODO Do something
//Dismiss once everything is OK.dialog.dismiss();}});}});dialog.show();
package com.droidahead.lib.utils;
import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.view.View;import android.view.View.OnClickListener;
public class CustomAlertDialogBuilder extends AlertDialog.Builder {/*** Click listeners*/private DialogInterface.OnClickListener mPositiveButtonListener = null;private DialogInterface.OnClickListener mNegativeButtonListener = null;private DialogInterface.OnClickListener mNeutralButtonListener = null;
/*** Buttons text*/private CharSequence mPositiveButtonText = null;private CharSequence mNegativeButtonText = null;private CharSequence mNeutralButtonText = null;
private DialogInterface.OnDismissListener mOnDismissListener = null;
private Boolean mCancelOnTouchOutside = null;
public CustomAlertDialogBuilder(Context context) {super(context);}
public CustomAlertDialogBuilder setOnDismissListener (DialogInterface.OnDismissListener listener) {mOnDismissListener = listener;return this;}
@Overridepublic CustomAlertDialogBuilder setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener) {mNegativeButtonListener = listener;mNegativeButtonText = text;return this;}
@Overridepublic CustomAlertDialogBuilder setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener) {mNeutralButtonListener = listener;mNeutralButtonText = text;return this;}
@Overridepublic CustomAlertDialogBuilder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) {mPositiveButtonListener = listener;mPositiveButtonText = text;return this;}
@Overridepublic CustomAlertDialogBuilder setNegativeButton(int textId, DialogInterface.OnClickListener listener) {setNegativeButton(getContext().getString(textId), listener);return this;}
@Overridepublic CustomAlertDialogBuilder setNeutralButton(int textId, DialogInterface.OnClickListener listener) {setNeutralButton(getContext().getString(textId), listener);return this;}
@Overridepublic CustomAlertDialogBuilder setPositiveButton(int textId, DialogInterface.OnClickListener listener) {setPositiveButton(getContext().getString(textId), listener);return this;}
public CustomAlertDialogBuilder setCanceledOnTouchOutside (boolean cancelOnTouchOutside) {mCancelOnTouchOutside = cancelOnTouchOutside;return this;}
@Overridepublic AlertDialog create() {throw new UnsupportedOperationException("CustomAlertDialogBuilder.create(): use show() instead..");}
@Overridepublic AlertDialog show() {final AlertDialog alertDialog = super.create();
DialogInterface.OnClickListener emptyOnClickListener = new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) { }};
// Enable buttons (needed for Android 1.6) - otherwise later getButton() returns nullif (mPositiveButtonText != null) {alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, mPositiveButtonText, emptyOnClickListener);}
if (mNegativeButtonText != null) {alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, mNegativeButtonText, emptyOnClickListener);}
if (mNeutralButtonText != null) {alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, mNeutralButtonText, emptyOnClickListener);}
// Set OnDismissListener if availableif (mOnDismissListener != null) {alertDialog.setOnDismissListener(mOnDismissListener);}
if (mCancelOnTouchOutside != null) {alertDialog.setCanceledOnTouchOutside(mCancelOnTouchOutside);}
alertDialog.show();
// Set the OnClickListener directly on the Button object, avoiding the auto-dismiss feature// IMPORTANT: this must be after alert.show(), otherwise the button doesn't exist..// If the listeners are null don't do anything so that they will still dismiss the dialog when clickedif (mPositiveButtonListener != null) {alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new OnClickListener() {
@Overridepublic void onClick(View v) {mPositiveButtonListener.onClick(alertDialog, AlertDialog.BUTTON_POSITIVE);}});}
if (mNegativeButtonListener != null) {alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new OnClickListener() {
@Overridepublic void onClick(View v) {mNegativeButtonListener.onClick(alertDialog, AlertDialog.BUTTON_NEGATIVE);}});}
if (mNeutralButtonListener != null) {alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new OnClickListener() {
@Overridepublic void onClick(View v) {mNeutralButtonListener.onClick(alertDialog, AlertDialog.BUTTON_NEUTRAL);}});}
return alertDialog;}}
编辑这是一个关于如何使用CustomAlertDialogBuilder的小示例:
// Create the CustomAlertDialogBuilderCustomAlertDialogBuilder dialogBuilder = new CustomAlertDialogBuilder(context);
// Set the usual data, as you would do with AlertDialog.BuilderdialogBuilder.setIcon(R.drawable.icon);dialogBuilder.setTitle("Dialog title");dialogBuilder.setMessage("Some text..");
// Set your buttons OnClickListenersdialogBuilder.setPositiveButton ("Button 1", new DialogInterface.OnClickListener() {public void onClick (DialogInterface dialog, int which) {// Do something...
// Dialog will not dismiss when the button is clicked// call dialog.dismiss() to actually dismiss it.}});
// By passing null as the OnClickListener the dialog will dismiss when the button is clicked.dialogBuilder.setNegativeButton ("Close", null);
// Set the OnDismissListener (if you need it)dialogBuilder.setOnDismissListener(new DialogInterface.OnDismissListener() {public void onDismiss(DialogInterface dialog) {// dialog was just dismissed..}});
// (optional) set whether to dismiss dialog when touching outsidedialogBuilder.setCanceledOnTouchOutside(false);
// Show the dialogdialogBuilder.show();
case ADD_CLIENT:LayoutInflater factoryClient = LayoutInflater.from(this);final View EntryViewClient = factoryClient.inflate(R.layout.alert_dialog_add_client, null);
EditText ClientText = (EditText) EntryViewClient.findViewById(R.id.client_edit);
AlertDialog.Builder builderClient = new AlertDialog.Builder(this);builderClient.setTitle(R.string.alert_dialog_client).setCancelable(false).setView(EntryViewClient).setPositiveButton("Save",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int whichButton) {EditText newClient = (EditText) EntryViewClient.findViewById(R.id.client_edit);String newClientString = newClient.getText().toString();if (checkForEmptyFields(newClientString)) {//If field is empty show toast and set error flag to true;Toast.makeText(getApplicationContext(),"Fields cant be empty",Toast.LENGTH_SHORT).show();add_client_error = true;} else {//Here save the info and set the error flag to falseadd_client_error = false;}}}).setNegativeButton("Cancel",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int id) {add_client_error = false;dialog.cancel();}});final AlertDialog alertClient = builderClient.create();alertClient.show();
alertClient.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Overridepublic void onDismiss(DialogInterface dialog) {//If the error flag was set to true then show the dialog againif (add_client_error == true) {alertClient.show();} else {return;}
}});return true;
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState){AlertDialog alertDialog = new AlertDialog(getActivity());// set more items...alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", null);
return alertDialog;}
@Overrideprotected void showDialog(Bundle state) {super.showDialog(state);
class mocl implements OnClickListener{private final AlertDialog dialog;public mocl(AlertDialog dialog) {this.dialog = dialog;}@Overridepublic void onClick(View v) {
//checks if EditText is empty, and if so tells the user via Toast//otherwise it closes dialog and calls the EditTextPreference's onClick//method to let it know that the button has been pressed
if (!IntPreference.this.getEditText().getText().toString().equals("")){dialog.dismiss();IntPreference.this.onClick(dialog,DialogInterface.BUTTON_POSITIVE);}else {Toast t = Toast.makeText(getContext(), "Enter a number!", Toast.LENGTH_SHORT);t.show();}
}}
AlertDialog d = (AlertDialog) getDialog();Button b = d.getButton(DialogInterface.BUTTON_POSITIVE);b.setOnClickListener(new mocl((d)));}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());builder.setMessage("Test for preventing dialog close");builder.setPositiveButton("Test",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){//Do nothing here because we override this button later to change the close behaviour.//However, we still need this because on older versions of Android unless we//pass a handler the button doesn't get instantiated}});final AlertDialog dialog = builder.create();dialog.show();//Overriding the handler immediately after show is probably a better approach than OnShowListener as described belowdialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){Boolean wantToCloseDialog = false;//Do stuff, possibly set wantToCloseDialog to true then...if(wantToCloseDialog)dialog.dismiss();//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.}});
对话片段-覆盖onResume()
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState){AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());builder.setMessage("Test for preventing dialog close");builder.setPositiveButton("Test",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){//Do nothing here because we override this button later to change the close behaviour.//However, we still need this because on older versions of Android unless we//pass a handler the button doesn't get instantiated}});return builder.create();}
//onStart() is where dialog.show() is actually called on//the underlying dialog, so we have to do it there or//later in the lifecycle.//Doing it in onResume() makes sure that even if there is a config change//environment that skips onStart then the dialog will still be functioning//properly after a rotation.@Overridepublic void onResume(){super.onResume();final AlertDialog d = (AlertDialog)getDialog();if(d != null){Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);positiveButton.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){Boolean wantToCloseDialog = false;//Do stuff, possibly set wantToCloseDialog to true then...if(wantToCloseDialog)d.dismiss();//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.}});}}
对话框首选项-覆盖showDialog()
@Overrideprotected void onPrepareDialogBuilder(Builder builder){super.onPrepareDialogBuilder(builder);builder.setPositiveButton("Test", this); //Set the button here so it gets created}
@Overrideprotected void showDialog(Bundle state){super.showDialog(state); //Call show on default first so we can override the handlers
final AlertDialog d = (AlertDialog) getDialog();d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View v){Boolean wantToCloseDialog = false;//Do stuff, possibly set wantToCloseDialog to true then...if(wantToCloseDialog)d.dismiss();//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.}});}
connectingDialog = new ProgressDialog(this);
connectingDialog.setCancelable(false);connectingDialog.setCanceledOnTouchOutside(false);
// Create the button but set the listener to a null object.connectingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",(DialogInterface.OnClickListener) null )
// Show the dialog so we can then get the button from the view.connectingDialog.show();
// Get the button from the view.Button dialogButton = connectingDialog.getButton( DialogInterface.BUTTON_NEGATIVE);
// Set the onClickListener here, in the view.dialogButton.setOnClickListener( new View.OnClickListener() {
@Overridepublic void onClick ( View v ) {
// Dialog will not get dismissed until you call dismiss() explicitly.
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(context);// ...final AlertDialog dialog = builder.create();dialog.show();// now you can override the default onClickListenerButton b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);b.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Log.i(TAG, "ok button is clicked");handleClick(dialog);}});
public void login(){final AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setView(R.layout.login_layout);builder.setTitle("Login");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int id){dialog.cancel();}});// put the negative button before the positive button, so it will appear
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int id){Dialog d = (Dialog) dialog;final EditText etUserName = (EditText) d.findViewById(R.id.etLoginName);final EditText etPassword = (EditText) d.findViewById(R.id.etLoginPassword);String userName = etUserName.getText().toString().trim();String password = etPassword.getText().toString().trim();
if (userName.isEmpty() || password.isEmpty()){
Toast.makeText(getApplicationContext(),"Please Fill all fields", Toast.LENGTH_SHORT).show();builder.show();// here after validation message before retrun// it will reopen the dialog// till the user enter the right conditionreturn;}
user = Manager.get(getApplicationContext()).getUserByName(userName);
if (user == null){Toast.makeText(getApplicationContext(),"Error ethier username or password are wrong", Toast.LENGTH_SHORT).show();builder.show();return;}if (password.equals(user.getPassword())){etPassword.setText("");etUserName.setText("");setLogged(1);setLoggedId(user.getUserId());Toast.makeText(getApplicationContext(),"Successfully logged in", Toast.LENGTH_SHORT).show();dialog.dismiss();// if every thing is ok then dismiss the dialog}else{Toast.makeText(getApplicationContext(),"Error ethier username or password are wrong", Toast.LENGTH_SHORT).show();builder.show();return;}
}});
builder.show();
}
import android.support.v4.app.DialogFragment;import android.support.v7.app.AlertDialog;
public class MyDialogFragment extends DialogFragment {
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {
// inflate the custom dialog layoutLayoutInflater inflater = getActivity().getLayoutInflater();View view = inflater.inflate(R.layout.my_dialog_layout, null);
// add a listener to the radio buttonsRadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup radioGroup, int i) {// enable the positive button after a choice has been madeAlertDialog dialog = (AlertDialog) getDialog();dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);}});
// build the alert dialogAlertDialog.Builder builder = new AlertDialog.Builder(getActivity());builder.setView(view).setPositiveButton("OK", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int id) {// TODO: use an interface to pass the user choice back to the activity}}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {MyDialogFragment.this.getDialog().cancel();}});return builder.create();}
@Overridepublic void onResume() {super.onResume();
// disable positive button by defaultAlertDialog dialog = (AlertDialog) getDialog();dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);}}
自定义对话框可以从这样的活动运行:
MyDialogFragment dialog = new MyDialogFragment();dialog.show(getFragmentManager(), "MyTag");
public class AddTopicFragment extends DialogFragment {
@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());// Get the layout inflaterLayoutInflater inflater = getActivity().getLayoutInflater();final View dialogView = inflater.inflate(R.layout.dialog_add_topic, null);
Button saveTopicDialogButton = (Button) dialogView.findViewById(R.id.saveTopicDialogButton);Button cancelSaveTopicDialogButton = (Button) dialogView.findViewById(R.id.cancelSaveTopicDialogButton);
final AppCompatEditText addTopicNameET = (AppCompatEditText) dialogView.findViewById(R.id.addTopicNameET);final AppCompatEditText addTopicCreatedByET = (AppCompatEditText) dialogView.findViewById(R.id.addTopicCreatedByET);
saveTopicDialogButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// validate inputsif(addTopicNameET.getText().toString().trim().isEmpty()){addTopicNameET.setError("Topic name can't be empty");addTopicNameET.requestFocus();}else if(addTopicCreatedByET.getText().toString().trim().isEmpty()){addTopicCreatedByET.setError("Topic created by can't be empty");addTopicCreatedByET.requestFocus();}else {// save topic to databaseTopic topic = new Topic();topic.name = addTopicNameET.getText().toString().trim();topic.createdBy = addTopicCreatedByET.getText().toString().trim();topic.createdDate = new Date().getTime();topic.save();AddTopicFragment.this.dismiss();}}});
cancelSaveTopicDialogButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {AddTopicFragment.this.dismiss();}});
// Inflate and set the layout for the dialog// Pass null as the parent view because its going in the dialog layoutbuilder.setView(dialogView).setMessage(getString(R.string.add_topic_message));
return builder.create();}
}
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); builder.setTitle("Internet Not Connected");if(ifConnected()){
Toast.makeText(this, "Connected or not", Toast.LENGTH_LONG).show();}else{builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {if(!ifConnected()){builder.show();}}}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {finish();}});builder.show();
}