Example usage for android.app AlertDialog getButton

List of usage examples for android.app AlertDialog getButton

Introduction

In this page you can find the example usage for android.app AlertDialog getButton.

Prototype

public Button getButton(int whichButton) 

Source Link

Document

Gets one of the buttons used in the dialog.

Usage

From source file:group.pals.android.lib.ui.filechooser.utils.ui.bookmark.BookmarkFragment.java

/**
 * Shows a dialog to let user enter new name or change current name of a
 * bookmark./*from ww w .  j  av a  2  s  .c o m*/
 * 
 * @param context
 *            {@link Context}
 * @param providerId
 *            the provider ID.
 * @param id
 *            the bookmark ID.
 * @param uri
 *            the URI to the bookmark.
 * @param name
 *            the name. To enter new name, this is the suggested name you
 *            provide. To rename, this is the old name.
 */
public static void doEnterNewNameOrRenameBookmark(final Context context, final String providerId, final int id,
        final Uri uri, final String name) {
    final AlertDialog dialog = Dlg.newDlg(context);

    View view = LayoutInflater.from(context).inflate(R.layout.afc_simple_text_input_view, null);
    final EditText textName = (EditText) view.findViewById(R.id.afc_text1);
    textName.setText(name);
    textName.selectAll();
    textName.setHint(R.string.afc_hint_new_name);
    textName.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Ui.showSoftKeyboard(textName, false);
                Button btn = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (btn.isEnabled())
                    btn.performClick();
                return true;
            }
            return false;
        }// onEditorAction()
    });

    dialog.setView(view);
    dialog.setIcon(R.drawable.afc_bookmarks_dark);
    dialog.setTitle(id < 0 ? R.string.afc_title_new_bookmark : R.string.afc_title_rename);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String newName = textName.getText().toString().trim();
                    if (android.text.TextUtils.isEmpty(newName)) {
                        Dlg.toast(context, R.string.afc_msg_bookmark_name_is_invalid, Dlg._LengthShort);
                        return;
                    }

                    Ui.showSoftKeyboard(textName, false);

                    ContentValues values = new ContentValues();
                    values.put(BookmarkContract.Bookmark._ColumnName, newName);

                    if (id >= 0) {
                        values.put(BookmarkContract.Bookmark._ColumnModificationTime,
                                DbUtils.formatNumber(new Date().getTime()));
                        context.getContentResolver()
                                .update(Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase,
                                        Uri.encode(Integer.toString(id))), values, null, null);
                    } else {
                        /*
                         * Check if the URI exists or doesn't. If it exists,
                         * update it instead of inserting the new one.
                         */
                        Cursor cursor = context.getContentResolver().query(
                                BookmarkContract.Bookmark._ContentUri, null,
                                String.format("%s = %s AND %s LIKE %s",
                                        BookmarkContract.Bookmark._ColumnProviderId,
                                        DatabaseUtils.sqlEscapeString(providerId),
                                        BookmarkContract.Bookmark._ColumnUri,
                                        DatabaseUtils.sqlEscapeString(uri.toString())),
                                null, null);
                        try {
                            if (cursor != null && cursor.moveToFirst()) {
                                values.put(BookmarkContract.Bookmark._ColumnModificationTime,
                                        DbUtils.formatNumber(new Date().getTime()));
                                context.getContentResolver().update(
                                        Uri.withAppendedPath(BookmarkContract.Bookmark._ContentIdUriBase,
                                                Uri.encode(cursor.getString(
                                                        cursor.getColumnIndex(BookmarkContract.Bookmark._ID)))),
                                        values, null, null);
                            } else {
                                values.put(BookmarkContract.Bookmark._ColumnProviderId, providerId);
                                values.put(BookmarkContract.Bookmark._ColumnUri, uri.toString());

                                context.getContentResolver().insert(BookmarkContract.Bookmark._ContentUri,
                                        values);
                            }
                        } finally {
                            if (cursor != null)
                                cursor.close();
                        }
                    }

                    Dlg.toast(context, context.getString(R.string.afc_msg_done), Dlg._LengthShort);
                }// onClick()
            });

    dialog.show();
    Ui.showSoftKeyboard(textName, true);

    final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    buttonOk.setEnabled(id < 0);

    textName.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            String newName = s.toString().trim();
            boolean enabled = !android.text.TextUtils.isEmpty(newName);
            buttonOk.setEnabled(enabled);

            /*
             * If renaming, only enable button OK if new name is not equal
             * to the old one.
             */
            if (enabled && id >= 0)
                buttonOk.setEnabled(!newName.equals(name));
        }
    });
}

From source file:com.haibison.android.anhuu.utils.ui.bookmark.BookmarkFragment.java

/**
 * Shows a dialog to let the user enter new name or change current name of a
 * bookmark.//from w  w  w.j a v a2  s .  c om
 * 
 * @param context
 *            {@link Context}
 * @param providerId
 *            the provider ID.
 * @param id
 *            the bookmark ID.
 * @param uri
 *            the URI to the bookmark.
 * @param name
 *            the name. To enter new name, this is the suggested name you
 *            provide. To rename, this is the old name.
 */
public static void doEnterNewNameOrRenameBookmark(final Context context, final String providerId, final int id,
        final Uri uri, final String name) {
    final AlertDialog dialog = Dlg.newAlertDlg(context);

    View view = LayoutInflater.from(context).inflate(R.layout.anhuu_f5be488d_simple_text_input_view, null);
    final EditText textName = (EditText) view.findViewById(R.id.anhuu_f5be488d_text1);
    textName.setText(name);
    textName.selectAll();
    textName.setHint(R.string.anhuu_f5be488d_hint_new_name);
    textName.setOnEditorActionListener(new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                UI.showSoftKeyboard(textName, false);
                Button btn = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (btn.isEnabled())
                    btn.performClick();
                return true;
            }
            return false;
        }// onEditorAction()
    });

    dialog.setView(view);
    dialog.setIcon(R.drawable.anhuu_f5be488d_bookmarks_dark);
    dialog.setTitle(id < 0 ? R.string.anhuu_f5be488d_title_new_bookmark : R.string.anhuu_f5be488d_title_rename);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String newName = textName.getText().toString().trim();
                    if (android.text.TextUtils.isEmpty(newName)) {
                        Dlg.toast(context, R.string.anhuu_f5be488d_msg_bookmark_name_is_invalid,
                                Dlg.LENGTH_SHORT);
                        return;
                    }

                    UI.showSoftKeyboard(textName, false);

                    ContentValues values = new ContentValues();
                    values.put(BookmarkContract.COLUMN_NAME, newName);

                    if (id >= 0) {
                        values.put(BookmarkContract.COLUMN_MODIFICATION_TIME,
                                DbUtils.formatNumber(new Date().getTime()));
                        context.getContentResolver().update(
                                ContentUris.withAppendedId(BookmarkContract.genContentIdUriBase(context), id),
                                values, null, null);
                    } else {
                        /*
                         * Check if the URI exists or doesn't. If it exists,
                         * update it instead of inserting the new one.
                         */
                        Cursor cursor = context.getContentResolver().query(
                                BookmarkContract.genContentUri(context), null,
                                String.format("%s = %s AND %s LIKE %s", BookmarkContract.COLUMN_PROVIDER_ID,
                                        DatabaseUtils.sqlEscapeString(providerId), BookmarkContract.COLUMN_URI,
                                        DatabaseUtils.sqlEscapeString(uri.toString())),
                                null, null);
                        try {
                            if (cursor != null && cursor.moveToFirst()) {
                                values.put(BookmarkContract.COLUMN_MODIFICATION_TIME,
                                        DbUtils.formatNumber(new Date().getTime()));
                                context.getContentResolver().update(
                                        Uri.withAppendedPath(BookmarkContract.genContentIdUriBase(context),
                                                Uri.encode(cursor.getString(
                                                        cursor.getColumnIndex(BookmarkContract._ID)))),
                                        values, null, null);
                            } else {
                                values.put(BookmarkContract.COLUMN_PROVIDER_ID, providerId);
                                values.put(BookmarkContract.COLUMN_URI, uri.toString());

                                context.getContentResolver().insert(BookmarkContract.genContentUri(context),
                                        values);
                            }
                        } finally {
                            if (cursor != null)
                                cursor.close();
                        }
                    }

                    Dlg.toast(context, context.getString(R.string.anhuu_f5be488d_msg_done), Dlg.LENGTH_SHORT);
                }// onClick()
            });

    dialog.show();
    UI.showSoftKeyboard(textName, true);

    final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    buttonOk.setEnabled(id < 0);

    textName.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            String newName = s.toString().trim();
            boolean enabled = !android.text.TextUtils.isEmpty(newName);
            buttonOk.setEnabled(enabled);

            /*
             * If renaming, only enable button OK if new name is not equal
             * to the old one.
             */
            if (enabled && id >= 0)
                buttonOk.setEnabled(!newName.equals(name));
        }
    });
}

From source file:br.com.bioscada.apps.biotracks.fragments.ChooseActivityTypeDialogFragment.java

public static Dialog getDialog(final Activity activity, final String category,
        final ChooseActivityTypeCaller caller) {
    View view = activity.getLayoutInflater().inflate(R.layout.choose_activity_type, null);
    GridView gridView = (GridView) view.findViewById(R.id.choose_activity_type_grid_view);
    final View weightContainer = view.findViewById(R.id.choose_activity_type_weight_container);

    TextView weightLabel = (TextView) view.findViewById(R.id.choose_activity_type_weight_label);
    weightLabel.setText(PreferencesUtils.isMetricUnits(activity) ? R.string.description_weight_metric
            : R.string.description_weight_imperial);

    final TextView weight = (TextView) view.findViewById(R.id.choose_activity_type_weight);

    List<Integer> imageIds = new ArrayList<Integer>();
    for (String iconValue : TrackIconUtils.getAllIconValues()) {
        imageIds.add(TrackIconUtils.getIconDrawable(iconValue));
    }/* ww  w. j  av a2 s.  c  o m*/

    Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(activity.getResources(), R.drawable.ic_track_airplane, options);
    int padding = 32;
    int width = options.outWidth + 2 * padding;
    int height = options.outHeight + 2 * padding;
    gridView.setColumnWidth(width);

    final ChooseActivityTypeImageAdapter imageAdapter = new ChooseActivityTypeImageAdapter(activity, imageIds,
            width, height, padding);
    gridView.setAdapter(imageAdapter);

    final String weightValue = StringUtils.formatWeight(PreferencesUtils.getWeightDisplayValue(activity));
    final AlertDialog alertDialog = new AlertDialog.Builder(activity)
            .setNegativeButton(R.string.generic_cancel, null)
            .setPositiveButton(R.string.generic_ok, new Dialog.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    boolean newWeight = false;
                    if (weightContainer.getVisibility() == View.VISIBLE) {
                        String newValue = weight.getText().toString();
                        if (!newValue.equals(weightValue)) {
                            newWeight = true;
                            PreferencesUtils.storeWeightValue(activity, newValue);
                        }
                    }
                    int selected = imageAdapter.getSelected();
                    caller.onChooseActivityTypeDone(TrackIconUtils.getAllIconValues().get(selected), newWeight);
                }
            }).setTitle(R.string.track_edit_activity_type_hint).setView(view).create();
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            int position = getPosition(activity, category);
            alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(position != -1);
            if (position != -1) {
                imageAdapter.setSelected(position);
                imageAdapter.notifyDataSetChanged();
            }
            updateWeightContainer(weightContainer, position);
            weight.setText(weightValue);
            DialogUtils.setDialogTitleDivider(activity, alertDialog);
        }
    });

    gridView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            alertDialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(true);
            imageAdapter.setSelected(position);
            imageAdapter.notifyDataSetChanged();
            updateWeightContainer(weightContainer, position);
        }
    });
    return alertDialog;
}

From source file:de.schildbach.wallet.ui.ReportIssueDialogFragment.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
    final Bundle args = getArguments();
    final int titleResId = args.getInt(KEY_TITLE);
    final int messageResId = args.getInt(KEY_MESSAGE);
    final String subject = args.getString(KEY_SUBJECT);
    final String contextualData = args.getString(KEY_CONTEXTUAL_DATA);

    final ReportIssueDialogBuilder builder = new ReportIssueDialogBuilder(activity, titleResId, messageResId) {
        @Override/*w  w  w  .j  av a 2  s.c o m*/
        protected String subject() {
            return subject + ": " + WalletApplication.versionLine(application.packageInfo());
        }

        @Override
        protected CharSequence collectApplicationInfo() throws IOException {
            final StringBuilder applicationInfo = new StringBuilder();
            appendApplicationInfo(applicationInfo, application);
            return applicationInfo;
        }

        @Override
        protected CharSequence collectStackTrace() throws IOException {
            final StringBuilder stackTrace = new StringBuilder();
            CrashReporter.appendSavedCrashTrace(stackTrace);
            return stackTrace.length() > 0 ? stackTrace : null;
        }

        @Override
        protected CharSequence collectDeviceInfo() throws IOException {
            final StringBuilder deviceInfo = new StringBuilder();
            appendDeviceInfo(deviceInfo, activity);
            return deviceInfo;
        }

        @Override
        protected CharSequence collectContextualData() {
            return contextualData;
        }

        @Override
        protected CharSequence collectWalletDump() {
            return viewModel.wallet.getValue().toString(false, true, true, null);
        }
    };
    final AlertDialog dialog = builder.create();

    dialog.setOnShowListener(new OnShowListener() {
        @Override
        public void onShow(final DialogInterface d) {
            positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            positiveButton.setEnabled(false);

            viewModel.wallet.observe(ReportIssueDialogFragment.this, new Observer<Wallet>() {
                @Override
                public void onChanged(final Wallet wallet) {
                    positiveButton.setEnabled(true);
                }
            });
        }
    });

    return dialog;
}

From source file:it.imwatch.nfclottery.dialogs.InsertContactDialog.java

/**
 * Sets the validation state of the form.
 *
 * @param validated When true, the confirmation button will be enabled;
 *                  when false, it will be disabled.
 *//*from ww w.  j  a v a2 s.  co m*/
private void setFormIsValidated(boolean validated) {
    final AlertDialog dialog = (AlertDialog) getDialog();
    if (dialog != null) {
        final Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);

        if (button != null) {
            button.setEnabled(validated);
        }
    }
}

From source file:id.satusatudua.sigap.ui.EnterCodeActivity.java

@OnClick(R.id.resend)
public void resendCode() {
    AlertDialog alertDialog = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.app_name).setMessage("Kirim ulang kode ke email anda?")
            .setPositiveButton("YA", (dialog, which) -> {
                presenter.resendCode();//from   w  ww  .  ja  va  2s.c  om
                dialog.dismiss();
            }).setNegativeButton("TIDAK", (dialog, which1) -> {
                dialog.dismiss();
            }).show();

    alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
            .setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
            .setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
    alertDialog.show();
}

From source file:id.satusatudua.sigap.ui.VerificationActivity.java

@OnClick(R.id.resend)
public void resendCode() {
    AlertDialog alertDialog = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
            .setTitle(R.string.app_name).setMessage("Kirim ulang kode ke email anda?")
            .setPositiveButton("YA", (dialog, which) -> {
                verificationPresenter.resendCode();
                dialog.dismiss();/*from   w w  w  . j a  v a2s  .c  o  m*/
            }).setNegativeButton("TIDAK", (dialog, which1) -> {
                dialog.dismiss();
            }).show();

    alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
            .setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
            .setTextColor(ContextCompat.getColor(this, R.color.colorPrimary));
    alertDialog.show();
}

From source file:com.dsi.ant.antplus.pluginsampler.geocache.Dialog_GeoProgramDevice.java

@Override
public void onStart() {
    super.onStart(); //super.onStart() is where dialog.show() is actually called on the underlying dialog, so we have to do it after this point
    AlertDialog d = (AlertDialog) getDialog();
    if (d != null) {
        Button positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override//from  w ww .  j  av  a  2  s. c  o m
            public void onClick(View v) {
                //Read in user set values
                final GeocacheDeviceData newDeviceData = new GeocacheDeviceData();

                if (checkBox_EnableIdString.isChecked())
                    newDeviceData.programmableData.identificationString = editText_IdString.getText()
                            .toString();

                if (checkBox_EnablePIN.isChecked())
                    newDeviceData.programmableData.PIN = Long.parseLong(editText_PIN.getText().toString());

                if (checkBox_EnableLatitude.isChecked())
                    newDeviceData.programmableData.latitude = new BigDecimal(
                            editText_Latitude.getText().toString());

                if (checkBox_EnableLongitude.isChecked())
                    newDeviceData.programmableData.longitude = new BigDecimal(
                            editText_Longitude.getText().toString());

                if (checkBox_EnableHintString.isChecked())
                    newDeviceData.programmableData.hintString = editText_HintString.getText().toString();

                if (checkBox_EnableLastVisit.isChecked()) {
                    newDeviceData.programmableData.numberOfVisits = Integer
                            .parseInt(editText_NumVisits.getText().toString());
                    newDeviceData.programmableData.lastVisitTimestamp = currentDisplayDatetime;
                }

                final Dialog_ProgressWaiter progressDialog = new Dialog_ProgressWaiter("Programming Device");

                //Use the current deviceID and PIN
                boolean reqSubmitted = geoPcc.requestDeviceProgramming(deviceData.deviceId,
                        deviceData.programmableData.PIN, radioButton_ClearExisitingData.isChecked(),
                        newDeviceData.programmableData, new AntPlusGeocachePcc.IProgrammingFinishedReceiver() {
                            @Override
                            public void onNewProgrammingFinished(GeocacheRequestStatus status) {
                                StringBuilder error = new StringBuilder("Error Programming: ");

                                switch (status) {
                                case SUCCESS:
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressDialog.dismiss();
                                            Bundle b = new Bundle();
                                            b.putParcelable(
                                                    GeocacheDeviceData.KEY_DEFAULT_GEOCACHEDEVICEDATAKEY,
                                                    newDeviceData);
                                            resultRcvr.send(0, b);
                                            dismiss();
                                        }
                                    });
                                    return;

                                case FAIL_DEVICE_COMMUNICATION_FAILURE:
                                    //When this occurs, it also results in the device being removed from the list,
                                    //we should bail to scan screen on this result
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            progressDialog.dismiss();
                                            resultRcvr.send(-1, null);
                                            dismiss();
                                        }
                                    });
                                    return;

                                case FAIL_DEVICE_NOT_IN_LIST:
                                    error.append("Device no longer in list");
                                    break;
                                case FAIL_ALREADY_BUSY_EXTERNAL:
                                    error.append("Device is busy");
                                    break;
                                case FAIL_BAD_PARAMS:
                                    error.append("Bad Parameters");
                                    break;
                                case FAIL_NO_PERMISSION:
                                    error.append("No Permission"); //shouldn't happen ever here because we always send matching PIN
                                    break;
                                case FAIL_DEVICE_DATA_NOT_DOWNLOADED:
                                    error.append("Device Data Not Downloaded");
                                    break;
                                case UNRECOGNIZED:
                                    //TODO This flag indicates that an unrecognized value was sent by the service, an upgrade of your PCC may be required to handle this new value.
                                    error.append("Unrecognized failure");
                                    break;
                                }

                                final String errorStr = error.toString();
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        progressDialog.dismiss();
                                        Toast.makeText(getActivity(), errorStr, Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                        }, progressDialog.getUpdateReceiver());

                if (reqSubmitted)
                    progressDialog.show(getActivity().getSupportFragmentManager(), "ProgrammingProgressDialog");
                else
                    Toast.makeText(getActivity(), "Error Programming Device: PCC already busy or dead",
                            Toast.LENGTH_SHORT).show();

                //now both dialogs stay open. They get closed in the programming result handler.
            }
        });
    }
}

From source file:se.frikod.payday.DailyBudgetFragment.java

public void editBudgetItem(final View v, final int currentIndex) {

    LayoutInflater inflater = activity.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.daily_budget_edit_budget_item, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
    builder.setTitle(getString(R.string.edit_budget_item_title));

    final BudgetItem budgetItem;
    final EditText titleView = (EditText) dialogView.findViewById(R.id.budget_item_title);
    final Spinner typeView = (Spinner) dialogView.findViewById(R.id.budget_item_type);
    final EditText amountView = (EditText) dialogView.findViewById(R.id.budget_item_amount);

    if (currentIndex == NEW_BUDGET_ITEM) {
        budgetItem = null;// w ww.jav  a  2  s  .  c  om
        builder.setTitle(getString(R.string.add_budget_item_dialog_title));
        builder.setPositiveButton(R.string.add_budget_item, null);
    } else {
        builder.setTitle(getString(R.string.edit_budget_item_title));

        budgetItem = budget.budgetItems.get(currentIndex);

        String title = budgetItem.title;
        BigDecimal amount = budgetItem.amount;
        int type;
        if (amount.signum() < 0) {
            type = 0;
            amount = amount.negate();
        } else {
            type = 1;
        }

        titleView.setText(title);
        typeView.setSelection(type);
        amountView.setText(amount.toString());

        builder.setNeutralButton(getString(R.string.delete_budget_item_yes),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                        budget.budgetItems.remove(currentIndex);
                        budget.saveBudgetItems();
                        updateBudgetItems();
                        dialog.dismiss();
                    }

                });
        builder.setPositiveButton(R.string.update_budget_item, null);
    }

    builder.setNegativeButton(getString(R.string.delete_budget_item_no), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    /* onClick listener for update needs to be setup like this to
       prevent closing dialog on error
     */

    final AlertDialog d = builder.create();
    d.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
            assert b != null;
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    BigDecimal amount;
                    try {
                        amount = new BigDecimal(amountView.getText().toString());
                        if (typeView.getSelectedItemId() == 0)
                            amount = amount.negate();
                    } catch (NumberFormatException e) {

                        Toast.makeText(activity.getApplicationContext(),
                                getString(R.string.new_budget_item_no_amount_specified), Toast.LENGTH_SHORT)
                                .show();

                        return;
                    }

                    String title = titleView.getText().toString();

                    if (budgetItem != null) {
                        budgetItem.amount = amount;
                        budgetItem.title = title;
                    } else {
                        budget.budgetItems.add(new BudgetItem(title, amount));
                    }

                    budget.saveBudgetItems();
                    updateBudgetItems();
                    d.dismiss();
                }
            });
        }
    });

    d.setView(dialogView);
    d.show();
}

From source file:de.spiritcroc.ownlog.ui.fragment.TagItemEditFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity activity = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final View view = activity.getLayoutInflater().inflate(R.layout.tag_edit_item, null);

    mEditTagName = (EditText) view.findViewById(R.id.name_edit);
    mEditTagDescription = (EditText) view.findViewById(R.id.description_edit);

    boolean restoredValues = restoreValues(savedInstanceState);

    builder.setTitle(mAddItem ? R.string.title_tag_item_add : R.string.title_tag_item_edit).setView(view)
            .setPositiveButton(R.string.dialog_ok, null)
            .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                @Override//from  w  w  w . jav  a 2s .  co  m
                public void onClick(DialogInterface dialog, int which) {
                    // Only dismiss (and hide keyboard)
                    hideKeyboard();
                }
            });
    if (!mAddItem) {
        builder.setNeutralButton(R.string.dialog_delete, null);
    }
    final AlertDialog alertDialog = builder.create();

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    saveChanges();
                }
            });
            if (!mAddItem) {
                alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                promptDelete();
                            }
                        });
            }
        }
    });

    if (!restoredValues) {
        // Edit text requires user interaction, so show keyboard
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

        if (mAddItem) {
            initValues();
        } else {
            loadContent();
        }
    }

    return alertDialog;
}