下面列出了怎么用android.app.AlertDialog的API类实例代码及写法,或者点击链接到github查看源代码。
public AlertDialog.Builder createBuilder() {
final Spinner mSpinner = new Spinner(mContext);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_dropdown_item, mList);
mSpinner.setAdapter(adapter);
mSpinner.setSelection(defaultPosition);
setTitle(mText);
setView(mSpinner);
setNegativeButton(mContext.getString(R.string.btn_cancel), null);
setPositiveButton(mContext.getString(R.string.btn_retry),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int n = mSpinner.getSelectedItemPosition();
dialogListener.select(n);
}
});
return this;
}
@Override
public void onStart() {
// super.onStart() is where dialog.show() is actually called on the underlying dialog,
// so we have to do the validation and handling of the positive button after this point
super.onStart();
Button positiveButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setEnabled(false);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<String> toDelete = new ArrayList<String>();
for (int i = 0; i < mProviderCount; i++) {
if (mCheckStates[i]) {
toDelete.add(mProviderUris.get(i));
}
}
getContract().onDeleteProviderClicked(toDelete);
dismiss();
}
});
}
public void SignupWithoutIDAlert() {
// Alert
AlertDialog.Builder builder = new AlertDialog.Builder(welcome.this);
builder.setMessage(getString(R.string.sign_up_without_id_des)).setTitle(
getString(R.string.alert));
builder.setPositiveButton(getString(R.string.continu),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(welcome.this, join.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton(getString(R.string.no), null);
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == kActivityRequestCode_EnableBluetooth) {
if (resultCode == Activity.RESULT_OK) {
checkPermissions();
} else if (resultCode == Activity.RESULT_CANCELED) {
if (!isFinishing()) {
hasUserAlreadyBeenAskedAboutBluetoothStatus = true; // Remember that
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.setMessage(R.string.bluetooth_poweredoff)
.setPositiveButton(android.R.string.ok, null)
.show();
DialogUtils.keepDialogOnOrientationChanges(dialog);
}
}
}
}
private void showOptionDialog(final AlertDialog dialog) {
final IBinder windowToken = KeyboardSwitcher.getInstance().getMainKeyboardView().getWindowToken();
if (windowToken == null) {
return;
}
final Window window = dialog.getWindow();
final WindowManager.LayoutParams lp = window.getAttributes();
lp.token = windowToken;
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog = dialog;
dialog.show();
}
/**
* 系统弹出提示框
*
* @param webView 浏览器
* @param message 提示信息
*/
public static void alert(WebView webView, String message) {
// 构建一个Builder来显示网页中的alert对话框
AlertDialog.Builder builder = new AlertDialog.Builder(webView.getContext());
builder.setTitle(webView.getContext().getString(R.string.dialog_title_system_msg));
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
}
@Test
public void testAddAccount() {
AccountManager.get(activity).addAccountExplicitly(new Account("existing",
BuildConfig.APPLICATION_ID), "password", null);
drawerAccount.performClick();
AlertDialog alertDialog = ShadowAlertDialog.getLatestAlertDialog();
assertNotNull(alertDialog);
assertThat(alertDialog.getListView().getAdapter()).hasCount(1);
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();
assertThat(alertDialog).isNotShowing();
((ShadowSupportDrawerLayout) Shadow.extract(activity.findViewById(R.id.drawer_layout)))
.getDrawerListeners().get(0)
.onDrawerClosed(activity.findViewById(R.id.drawer));
assertThat(shadowOf(activity).getNextStartedActivity())
.hasComponent(activity, LoginActivity.class);
}
private void onEnterStartedState() {
Log.d(TAG, "call onEnterStartedState");
/* Connect camera */
if (!connectCamera(getWidth(), getHeight())) {
AlertDialog ad = new AlertDialog.Builder(getContext()).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("It seems that you device does not support camera (or it is locked). Application will be closed.");
ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
((Activity) getContext()).finish();
}
});
ad.show();
}
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
Bundle args = getArguments();
String msg = "";
if (args != null) {
msg = args.getString(EXTRA_MSG);
}
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_setting_progress, null);
TextView messageView = v.findViewById(R.id.message);
messageView.setText(msg);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
private void sendMessage() {
EditText textEntry = (EditText) getView().findViewById(R.id.text_entry);
final String text = textEntry.getText().toString();
if (TextUtils.isEmpty(text)) {
return;
}
if (text.startsWith("/")) {
new AlertDialog.Builder(getActivity())
.setMessage(R.string.commands_not_supported)
.setPositiveButton(android.R.string.ok, null)
.show();
return;
}
textEntry.setText("");
mConnection.say(mBuffer.getName(), text, null);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder;
if (dialogStyle == DIALOG_STYLE_MATERIAL) {
builder = new AlertDialog.Builder(getContext());
if (!TextUtils.isEmpty(title)) {
builder.setTitle(title);
}
if (cancelListener != null) {
builder.setNegativeButton(cancelText, cancelListener);
}
if (okListener != null) {
builder.setPositiveButton(okText, okListener);
}
initMaterialDialog(builder);
} else {
builder = new AlertDialog.Builder(getContext(), R.style.CommonDialog);
initCustomDialog(builder);
}
return builder.create();
}
@NonNull
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
if (alreadyCreated) return getDialog();
alreadyCreated = true;
final Context context = getContext();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.options_past));
rv = new RecyclerView(context);
builder.setView(rv);
rv.setLayoutManager(new LinearLayoutManager(context));
rv.setAdapter(new SessionListAdapter(context, url, current, type, this));
rv.setHasFixedSize(true);
RedditAccountManager.getInstance(context).addUpdateListener(this);
builder.setNeutralButton(context.getString(R.string.dialog_close), null);
return builder.create();
}
/**
* Shares the given text by encoding it as a barcode, such that another user can
* scan the text off the screen of the device.
*
* @param text the text string to encode as a barcode
* @param type type of data to encode. See {@code com.google.zxing.client.android.Contents.Type} constants.
* @return the {@link AlertDialog} that was shown to the user prompting them to download the app
* if a prompt was needed, or null otherwise
*/
public final AlertDialog shareText(CharSequence text, CharSequence type) {
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setAction(BS_PACKAGE + ".ENCODE");
intent.putExtra("ENCODE_TYPE", type);
intent.putExtra("ENCODE_DATA", text);
String targetAppPackage = findTargetAppPackage(intent);
if (targetAppPackage == null) {
return showDownloadDialog();
}
intent.setPackage(targetAppPackage);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
attachMoreExtras(intent);
if (fragment == null) {
activity.startActivity(intent);
} else {
fragment.startActivity(intent);
}
return null;
}
private void onNavigateButtonClick(Button source) {
activeTab = source.getText().toString();
logicGroup.setVisibility(getGroupVisibility(source, logicButton));
friendsGroup.setVisibility(getGroupVisibility(source, friendsButton));
settingsGroup.setVisibility(getGroupVisibility(source, settingsButton));
contentGroup.setVisibility(getGroupVisibility(source, contentButton));
// Show an error if viewing friends and there is no logged in user.
if (source == friendsButton) {
Session session = Session.getActiveSession();
if ((session == null) || !session.isOpened()) {
new AlertDialog.Builder(this)
.setTitle(R.string.feature_requires_login_title)
.setMessage(R.string.feature_requires_login_message)
.setPositiveButton(R.string.ok_button, null)
.show();
}
}
}
public void showUpgradeMessage () {
if (TextUtils.isEmpty(Preferences.getValue("showUpgradeMessage"))) {
android.support.v7.app.AlertDialog alertDialog = new android.support.v7.app.AlertDialog.Builder(this).create();
alertDialog.setTitle(R.string.welcome_message);
alertDialog.setMessage(this.getString(R.string.upgrade_message));
alertDialog.setButton(android.support.v7.app.AlertDialog.BUTTON_NEUTRAL, this.getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("showUpgradeMessage","false").commit();
}
}
private final void loadResError() {
AlertDialog.Builder dia = new AlertDialog.Builder(this);
ResoureFinder finder = ResoureFinder.getInstance();
dia.setTitle(finder.getString(this, "browser_dialog_error"));
dia.setMessage(finder.getString(this, "browser_init_error"));
dia.setCancelable(false);
dia.setPositiveButton(finder.getString(this, "confirm"),
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
Process.killProcess(Process.myPid());
}
});
dia.create();
dia.show();
}
private void showAlert(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Face Detection Training");
alertDialogBuilder
.setMessage("Ten samples should be for saving!")
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
@Override
public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frame_trivia_game);
if (fragment instanceof TriviaGameErrorFragment) {
super.onBackPressed();
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.ui_quit_game)
.setMessage(R.string.ui_quit_game_msg)
.setPositiveButton(android.R.string.yes, (dialog, which) ->
TriviaGameActivity.super.onBackPressed())
.setNegativeButton(android.R.string.no, (dialog, which) -> {
})
.show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} else if (id ==R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPostExecute(Exception exc) {
// Activity died?
if (isFinishing()) {
return;
}
// Hide progress bar
mLoading.dismiss();
// Registration failed?
if (exc != null) {
// Write error to logcat
Log.e("Pushy", "Registration failed: " + exc.getMessage());
// Display error dialog
new AlertDialog.Builder(Main.this).setTitle(R.string.registrationError)
.setMessage(exc.getMessage())
.setPositiveButton(R.string.ok, null)
.create()
.show();
}
// Update UI with registration result
updateUI();
}
/**
* Prompt user whether to proceed or not, if so, execute runnable
*
* @param context
* @param titleResId
* @param msgResId
* @param onConfirm
*/
public static void confirm(Context context, String logTag, int titleResId, int msgResId,
int OkResId, int cancelResId, final Runnable onConfirm) {
AlertDialog dialog = null;
try {
Builder b = new Builder(context);
b.setCancelable(true);
if (titleResId >= 0) b.setTitle(titleResId);
if (msgResId >= 0) b.setMessage(msgResId);
if (cancelResId >= 0) b.setNegativeButton(cancelResId, null);
if (onConfirm != null && OkResId >= 0) b.setPositiveButton(OkResId, new OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
onConfirm.run();
}
});
b.create().show();
} catch (Exception e) {
if (logTag != null) Utils.handleException(logTag, context, e);
}
}
public static void add(final char unicode) {
final EditText editText = new EditText(activity);
editText.setHint(R.string.favorite_add_hint);
editText.setSingleLine(false);
new AlertDialog.Builder(activity)
.setIcon(R.drawable.ic_star_yellow)
.setTitle(String.format(activity.getString(R.string.favorite_add), unicode))
.setView(editText)
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String comment = editText.getText().toString();
UserDatabase.insertFavorite(unicode, comment);
String message = String.format(activity.getString(R.string.favorite_add_done), unicode);
Boast.showText(activity, message, Toast.LENGTH_SHORT);
FavoriteFragment fragment = activity.getFavoriteFragment();
if (fragment != null) {
fragment.notifyAddItem();
}
activity.getCurrentFragment().refresh();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private void eventDeal() {
AppUser appUser = BmobUser.getCurrentUser(AppUser.class);
String avatarUrl = appUser.getUserAvatarUrl();
Glide.with(MeAvatarShowerAty.this)
.load(avatarUrl)
.error(R.drawable.app_icon)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(avatarImv);
photoViewAttacher = new PhotoViewAttacher(avatarImv);
photoViewAttacher.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
String[] choices = {"保存至本地"};
//包含多个选项的对话框
AlertDialog dialog = new AlertDialog.Builder(MeAvatarShowerAty.this)
.setItems(choices, onselect).create();
dialog.show();
return true;
}
});
}
private void initShell()
{
ShellUnit.initBusybox(getResources().openRawResource(R.raw.busybox));
if(!ShellUnit.sRootReady)
new AlertDialog.Builder(this).setTitle(R.string.error).setMessage(R.string.no_root_tip)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
FrameActivity.this.finish();
}
}).create().show();
if(!ShellUnit.sSuReady||!ShellUnit.sBusyboxReady)
Toast.makeText(this,getString(R.string.init_fail),Toast.LENGTH_LONG).show();
logInfo("SUReady="+ShellUnit.sSuReady+";BusyboxReady="+ShellUnit.sBusyboxReady);
ShellUnit.execBusybox("echo 'initShell finished'");
}
private void onEnterStartedState() {
Log.d(TAG, "call onEnterStartedState");
/* Connect camera */
if (!connectCamera(getWidth(), getHeight())) {
AlertDialog ad = new AlertDialog.Builder(getContext()).create();
ad.setCancelable(false); // This blocks the 'BACK' button
ad.setMessage("It seems that you device does not support camera (or it is locked). Application will be closed.");
ad.setButton(DialogInterface.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
((Activity) getContext()).finish();
}
});
ad.show();
}
}
/**
* Prompt the user to enable location if it isn't already on.
*
* @param parent The currently visible activity.
*/
public static void requestLocation(final Activity parent) {
if (LocationHelper.isLocationEnabled(parent)) {
return;
}
// Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533
AlertDialog.Builder builder = new AlertDialog.Builder(parent);
builder.setTitle(R.string.location_not_found_title);
builder.setMessage(R.string.location_not_found_message);
builder.setPositiveButton(R.string.location_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton(R.string.no, null);
try {
builder.create().show();
} catch (RuntimeException e) {
Looper.prepare();
builder.create().show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
builder.setView(input);
builder.setTitle(R.string.blacklist_add);
builder.setMessage(R.string.blacklist_desc);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
//@Override
public void onClick(DialogInterface dialog, int which) {
Editable value = input.getText();
addEntry(value.toString());
}
});
builder.show();
return super.onOptionsItemSelected(item);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle arguments = getArguments();
final int requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE);
finishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY);
return new AlertDialog.Builder(getActivity())
.setMessage(R.string.permission_rationale_location)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// After click on Ok, request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
requestCode);
// Do not finish the Activity while requesting permission.
finishActivity = false;
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
private void showDialog(Cursor cursor) {
int size = cursor.getInt(cursor.getColumnIndexOrThrow(Downloads.COLUMN_TOTAL_BYTES));
String sizeString = Formatter.formatFileSize(this, size);
String queueText = "Queue";
boolean isWifiRequired =
mCurrentIntent.getExtras().getBoolean(DownloadInfo.EXTRA_IS_WIFI_REQUIRED);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// if (isWifiRequired) {
// builder.setTitle(R.string.wifi_required_title)
// .setMessage(getString(R.string.wifi_required_body, sizeString, queueText))
// .setPositiveButton(R.string.button_queue_for_wifi, this)
// .setNegativeButton(R.string.button_cancel_download, this);
// } else {
// builder.setTitle(R.string.wifi_recommended_title)
// .setMessage(getString(R.string.wifi_recommended_body, sizeString, queueText))
// .setPositiveButton(R.string.button_start_now, this)
// .setNegativeButton(R.string.button_queue_for_wifi, this);
// }
mDialog = builder.setOnCancelListener(this).show();
}
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d("Error: %d, %d", framework_err, impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mMediaController != null)
mMediaController.hide();
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err))
return true;
}
if (getWindowToken() != null) {
int message = framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK ? getResources().getIdentifier("VideoView_error_text_invalid_progressive_playback", "string", mContext.getPackageName()): getResources().getIdentifier("VideoView_error_text_unknown", "string", mContext.getPackageName());
new AlertDialog.Builder(mContext).setTitle(getResources().getIdentifier("VideoView_error_title", "string", mContext.getPackageName())).setMessage(message).setPositiveButton(getResources().getIdentifier("VideoView_error_button", "string", mContext.getPackageName()), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (mOnCompletionListener != null)
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}).setCancelable(false).show();
}
return true;
}