Example usage for android.app AlertDialog setOnShowListener

List of usage examples for android.app AlertDialog setOnShowListener

Introduction

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

Prototype

public void setOnShowListener(@Nullable OnShowListener listener) 

Source Link

Document

Sets a listener to be invoked when the dialog is shown.

Usage

From source file:io.github.tjg1.nori.fragment.AddTagFilterDialogFragment.java

@NonNull
@SuppressLint("InflateParams")
@Override/*w w  w .  j  a  v  a2 s.c o m*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Inflate the Dialog view XML.
    final LayoutInflater inflater = LayoutInflater.from(getContext());
    final View view = inflater.inflate(R.layout.dialog_add_tag_filter, null);
    tagEditText = (EditText) view.findViewById(R.id.editText);

    // Restore preserved text from savedInstanceState, if possible.
    if (savedInstanceState != null && savedInstanceState.containsKey(BUNDLE_ID_TAG_FILTER)) {
        tagEditText.setText(savedInstanceState.getString(BUNDLE_ID_TAG_FILTER));
    }

    // Create the AlertDialog object.
    final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setView(view)
            .setPositiveButton(R.string.action_add, null)
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Dismiss dialog.
                    dismiss();
                }
            }).create();

    // onShowListener is used here as a hack to override Android DialogInterface's default onClickInterface
    // that doesn't provide a way to prevent the dialog from getting dismissed when a button is clicked.
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                    .setOnClickListener(AddTagFilterDialogFragment.this);
        }
    });

    return alertDialog;
}

From source file:hku.fyp14017.blencode.ui.dialogs.NewSpriteDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    dialogView = LayoutInflater.from(getActivity()).inflate(hku.fyp14017.blencode.R.layout.dialog_new_object,
            null);//  w  w w.  j  a  va2  s.  c  o  m
    setupPaintroidButton(dialogView);
    setupGalleryButton(dialogView);
    setupCameraButton(dialogView);

    AlertDialog dialog = null;
    AlertDialog.Builder dialogBuilder = new CustomAlertDialogBuilder(getActivity()).setView(dialogView)
            .setTitle(hku.fyp14017.blencode.R.string.new_sprite_dialog_title);
    if (wizardStep == DialogWizardStep.STEP_1) {
        dialog = createDialogStepOne(dialogBuilder);
    } else if (wizardStep == DialogWizardStep.STEP_2) {
        dialog = createDialogStepTwo(dialogBuilder);
    }
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(final DialogInterface dialog) {
            Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
            button.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    if (handleOkButton()) {
                        dialog.dismiss();
                    }
                }
            });
        }
    });
    dialog.setCanceledOnTouchOutside(true);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    return dialog;
}

From source file:com.dattasmoon.pebble.plugin.EditNotificationActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Selected menu item id: " + String.valueOf(item.getItemId()));
    }//from  w w w .  j  a  v a 2  s  .c om
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View v;
    ListViewHolder viewHolder;
    AdapterView.AdapterContextMenuInfo contextInfo;
    String app_name;
    final String package_name;
    switch (item.getItemId()) {
    case R.id.btnUncheckAll:

        builder.setTitle(R.string.dialog_confirm_title);
        builder.setMessage(getString(R.string.dialog_uncheck_message));
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                if (lvPackages == null || lvPackages.getAdapter() == null
                        || ((packageAdapter) lvPackages.getAdapter()).selected == null) {
                    //something went wrong
                    return;
                }
                ((packageAdapter) lvPackages.getAdapter()).selected.clear();
                lvPackages.invalidateViews();
            }
        });
        builder.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                //do nothing!
            }
        });
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        builder.show();

        return true;
    case R.id.btnSave:
        finish();
        return true;
    case R.id.btnDonate:
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData(Uri.parse(Constants.DONATION_URL));
        startActivity(i);
        return true;
    case R.id.btnSettings:
        Intent settings = new Intent(this, SettingsActivity.class);
        startActivity(settings);
        return true;
    case R.id.btnRename:
        contextInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = contextInfo.position;
        long id = contextInfo.id;
        // the child view who's info we're viewing (should be equal to v)
        v = contextInfo.targetView;
        app_name = ((TextView) v.findViewById(R.id.tvPackage)).getText().toString();
        viewHolder = (ListViewHolder) v.getTag();
        if (viewHolder == null || viewHolder.chkEnabled == null) {
            //failure
            return true;
        }
        package_name = (String) viewHolder.chkEnabled.getTag();
        builder.setTitle(R.string.dialog_title_rename_notification);
        final EditText input = new EditText(this);
        input.setHint(app_name);
        builder.setView(input);
        builder.setPositiveButton(R.string.confirm, null);
        builder.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do nothing
            }
        });
        final AlertDialog d = builder.create();
        d.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
                if (b != null) {
                    b.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //can't be nothing
                            if (input.getText().length() > 0) {
                                if (Constants.IS_LOGGABLE) {
                                    Log.i(Constants.LOG_TAG,
                                            "Adding rename for " + package_name + " to " + input.getText());
                                }
                                JSONObject rename = new JSONObject();
                                try {
                                    rename.put("pkg", package_name);
                                    rename.put("to", input.getText());
                                    arrayRenames.put(rename);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                ((packageAdapter) lvPackages.getAdapter()).notifyDataSetChanged();

                                d.dismiss();
                            } else {
                                input.setText(R.string.error_cant_be_blank);
                            }

                        }
                    });
                }
            }
        });

        d.show();

        return true;
    case R.id.btnRemoveRename:
        contextInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        // the child view who's info we're viewing (should be equal to v)
        v = contextInfo.targetView;
        app_name = ((TextView) v.findViewById(R.id.tvPackage)).getText().toString();
        viewHolder = (ListViewHolder) v.getTag();
        if (viewHolder == null || viewHolder.chkEnabled == null) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Viewholder is null or chkEnabled is null");
            }
            //failure
            return true;
        }
        package_name = (String) viewHolder.chkEnabled.getTag();
        builder.setTitle(
                getString(R.string.dialog_title_remove_rename) + app_name + " (" + package_name + ")?");
        builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Before remove is: " + String.valueOf(arrayRenames.length()));
                }
                JSONArray tmp = new JSONArray();
                try {
                    for (int i = 0; i < arrayRenames.length(); i++) {
                        if (!arrayRenames.getJSONObject(i).getString("pkg").equalsIgnoreCase(package_name)) {
                            tmp.put(arrayRenames.getJSONObject(i));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                arrayRenames = tmp;
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "After remove is: " + String.valueOf(arrayRenames.length()));
                }
                ((packageAdapter) lvPackages.getAdapter()).notifyDataSetChanged();
            }
        });
        builder.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //do nothing
            }
        });
        builder.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.DeploymentsViewFragment.java

public void showLocalDeploymentsOptionsMenu() {
    File root = application.getLocalDeploymentsDirectory();

    final String[] files = root.list();

    if (files.length == 0) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

        alertDialog.setTitle(R.string.directory_empty_title)
                .setMessage(String.format(getString(R.string.directory_empty_msg), root.getAbsolutePath()))
                .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                .setIcon(android.R.drawable.ic_dialog_alert).show();

        return;//from  ww  w .  j  ava  2s.co m
    }

    Arrays.sort(files);

    // time to display the list of files
    AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity());

    filesDialog.setTitle(R.string.upload_deployment_step1);

    filesDialog.setSingleChoiceItems(files, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            // enable button if a deployment is clicked
            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
        }
    });

    // Cancel Button
    filesDialog.setNegativeButton(R.string.cancel, null);

    // Upload Button
    filesDialog.setPositiveButton(R.string.action_upload, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            int selectedPosition = ((AlertDialog) dialogInterface).getListView().getCheckedItemPosition();

            uploadDeployment(files[selectedPosition]);
        }
    });
    filesDialog.setCancelable(true);

    AlertDialog dialog = filesDialog.create();
    // initially show upload button disabled
    // wait until a deployment is enabled
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        }
    });

    dialog.show();
}

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

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Activity activity = getActivity();
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final View view = createView();

    restoreValues(savedInstanceState);/* w  w  w .  ja  v a 2s.c om*/
    loadContent();

    final AlertDialog alertDialog = builder.setTitle(R.string.dialog_select_tags).setView(view)
            .setPositiveButton(R.string.dialog_save_changes, null)
            .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Only dismiss
                }
            }).setNeutralButton(R.string.dialog_add, null).create();

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            saveChanges();
                        }
                    });
            alertDialog.getButton(DialogInterface.BUTTON_NEUTRAL)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            new TagItemEditFragment().setShouldHideKeyboardOnDismiss(true)
                                    .show(getFragmentManager(), "TagItemEditFragment");
                        }
                    });
        }
    });

    return alertDialog;
}

From source file:com.cuddlesoft.nori.fragment.EditAPISettingDialogFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Get database row ID of the object being edited (if any) from the arguments bundle.
    if (getArguments() != null && getArguments().containsKey(BUNDLE_ID_ROW_ID)) {
        rowId = getArguments().getLong(BUNDLE_ID_ROW_ID);
    }//from  w w  w .  j a v  a  2 s .  c o  m

    // Inflate XML for the dialog's main view.
    LayoutInflater inflater = LayoutInflater.from(getActivity());
    @SuppressLint("InflateParams")
    View view = inflater.inflate(R.layout.dialog_edit_api_setting, null, false);

    // Get references to the parent view's subviews.
    name = (AutoCompleteTextView) view.findViewById(R.id.name);
    uri = (EditText) view.findViewById(R.id.uri);
    username = (EditText) view.findViewById(R.id.username);
    passphrase = (EditText) view.findViewById(R.id.passphrase);

    // Set service name autosuggestion adapter.
    name.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.simple_dropdown_item,
            getResources().getStringArray(R.array.service_suggestions_names)));
    name.setThreshold(1);
    name.setOnItemClickListener(this);

    // Set service URI TextChangedListener to show optional authentication fields when the Danbooru endpoint is used.
    uri.addTextChangedListener(this);
    // Set service URI OnFocusChangeListener to prepend "http://" to the text field when the user clicks on it.
    uri.setOnFocusChangeListener(this);

    // Populate views from an existing SearchClient.Settings object, if it was passed in the arguments bundle.
    if (savedInstanceState == null && getArguments() != null
            && getArguments().containsKey(BUNDLE_ID_SETTINGS)) {
        // Get the SearchClient.Settings object from this fragment's arguments bundle.
        SearchClient.Settings settings = getArguments().getParcelable(BUNDLE_ID_SETTINGS);

        // Populate subviews with content.
        name.setText(settings.getName());
        uri.setText(settings.getEndpoint());
        username.setText(settings.getUsername());
        passphrase.setText(settings.getPassword());
    }

    // Dismiss dropdown when the view is first shown.
    name.dismissDropDown();

    // Create the AlertDialog object.
    final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setView(view)
            .setTitle(rowId == -1 ? R.string.dialog_title_addService : R.string.dialog_title_editService)
            .setPositiveButton(R.string.ok, null)
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Dismiss dialog without saving changes.
                    dismiss();
                }
            }).create();

    // Use OnShowListener to override positive button behaviour.
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            // OnShowListener here is used as a hack to override Android Dialog's default OnClickListener
            // that doesn't provide a way to prevent the dialog from getting dismissed when a button is clicked.
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                    .setOnClickListener(EditAPISettingDialogFragment.this);
        }
    });

    return alertDialog;
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.DeploymentsViewFragment.java

public void addDeploymentToGroup(final Deployment deployment) {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchDomainGroups(new Callback() {
        @Override/*from   www.ja  v  a  2s  .  c om*/
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            JsonObject jsonObj = reply.getAsJsonObject();

            final List<String> groups = new ArrayList<String>();
            for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                groups.add(e.getKey());
            }

            // time to display the list
            AlertDialog.Builder groupsDialog = new AlertDialog.Builder(getActivity());

            groupsDialog.setTitle(R.string.add_deployment_to_group);
            groupsDialog.setMultiChoiceItems(groups.toArray(new String[groups.size()]),
                    new boolean[groups.size()], new DialogInterface.OnMultiChoiceClickListener() {
                        public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                            int selected = ((AlertDialog) dialogInterface).getListView().getCheckedItemCount();

                            // disable or enable buttons depending on the
                            // number of items checked.
                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL)
                                    .setEnabled(selected != 0);
                            ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE)
                                    .setEnabled(selected != 0);
                        }

                    });

            // Cancel Button
            groupsDialog.setNegativeButton(R.string.cancel, null);

            // Add to Group Button
            groupsDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int k) {
                    addDeployment(deployment, false, getSelectedItems(dialogInterface));
                }
            });

            // Add to Group and Enable Button
            groupsDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    addDeployment(deployment, true, getSelectedItems(dialogInterface));
                }
            });
            groupsDialog.setCancelable(true);

            AlertDialog dialog = groupsDialog.create();
            // initially show add* buttons disabled
            // wait until a deployment is enabled
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false);
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                }
            });

            dialog.show();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}

From source file:org.cvasilak.jboss.mobile.admin.fragments.DeploymentsViewFragment.java

public void showRepositoryDeploymentsOptionsMenu() {
    progress = ProgressDialog.show(getSherlockActivity(), "", getString(R.string.queryingServer));

    application.getOperationsManager().fetchDeployments(null, new Callback() {
        @Override/* w w w.j av a2s  .  c  om*/
        public void onSuccess(JsonElement reply) {
            progress.dismiss();

            String name, runtimeName, BYTES_VALUE;
            boolean enabled = false;

            JsonObject jsonObj = reply.getAsJsonObject();

            final ArrayAdapter<Deployment> repoAdapter = new ArrayAdapter<Deployment>(getActivity(),
                    android.R.layout.simple_list_item_single_choice);

            for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                name = e.getKey();

                JsonObject detailsJsonObj = e.getValue().getAsJsonObject();

                if (detailsJsonObj.get("enabled") != null)
                    enabled = detailsJsonObj.get("enabled").getAsBoolean();

                runtimeName = detailsJsonObj.get("runtime-name").getAsString();

                // "content" : [{"hash" : { "BYTES_VALUE" : "Pb4xyzgJmsxruKEf5eGOLu6lBjw="}}],
                BYTES_VALUE = detailsJsonObj.get("content").getAsJsonArray().get(0).getAsJsonObject()
                        .get("hash").getAsJsonObject().get("BYTES_VALUE").getAsString();

                repoAdapter.add(new Deployment(name, runtimeName, enabled, BYTES_VALUE));
            }

            // time to display content repository
            AlertDialog.Builder filesDialog = new AlertDialog.Builder(getActivity());

            filesDialog.setTitle(R.string.add_deployment_from_repository);
            filesDialog.setSingleChoiceItems(repoAdapter, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // enable buttons if a deployment is clicked
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(true);
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                }
            });

            // Cancel Button
            filesDialog.setNegativeButton(R.string.cancel, null);

            // Add to Group Button
            filesDialog.setNeutralButton(R.string.add_to_group, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int selectedPosition = ((AlertDialog) dialogInterface).getListView()
                            .getCheckedItemPosition();

                    addDeployment(repoAdapter.getItem(selectedPosition), false, Arrays.asList(group));
                }
            });

            // Add to Group and Enable Button
            filesDialog.setPositiveButton(R.string.add_to_group_enable, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    int selectedPosition = ((AlertDialog) dialogInterface).getListView()
                            .getCheckedItemPosition();

                    addDeployment(repoAdapter.getItem(selectedPosition), true, Arrays.asList(group));
                }
            });
            filesDialog.setCancelable(true);

            AlertDialog dialog = filesDialog.create();
            // initially show add* buttons disabled
            // wait until a deployment is enabled
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialogInterface) {
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_NEUTRAL).setEnabled(false);
                    ((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                }
            });

            dialog.show();
        }

        @Override
        public void onFailure(Exception e) {
            progress.dismiss();

            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());

            alertDialog.setTitle(R.string.dialog_error_title).setMessage(e.getMessage())
                    .setPositiveButton(R.string.dialog_button_Bummer, null).setCancelable(false)
                    .setIcon(android.R.drawable.ic_dialog_alert).show();

        }
    });
}

From source file:io.github.tjg1.nori.fragment.EditAPISettingDialogFragment.java

@NonNull
@Override/*from   ww w. ja  v  a2  s .c  om*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Get database row ID of the object being edited (if any) from the arguments bundle.
    if (getArguments() != null && getArguments().containsKey(BUNDLE_ID_ROW_ID)) {
        rowId = getArguments().getLong(BUNDLE_ID_ROW_ID);
    }

    // Inflate XML for the dialog's main view.
    LayoutInflater inflater = LayoutInflater.from(getContext());
    @SuppressLint("InflateParams")
    View view = inflater.inflate(R.layout.dialog_edit_api_setting, null, false);

    // Get references to the parent view's subviews.
    name = (AutoCompleteTextView) view.findViewById(R.id.name);
    uri = (EditText) view.findViewById(R.id.uri);
    username = (EditText) view.findViewById(R.id.username);
    passphrase = (EditText) view.findViewById(R.id.passphrase);

    // Set service name autosuggestion adapter.
    name.setAdapter(new ArrayAdapter<>(getContext(), R.layout.api_suggestion_dropdown_item,
            getResources().getStringArray(R.array.service_suggestions_names)));
    name.setThreshold(1);
    name.setOnItemClickListener(this);

    // Set service URI TextChangedListener to show optional authentication fields when the Danbooru endpoint is used.
    uri.addTextChangedListener(this);
    // Set service URI OnFocusChangeListener to prepend "http://" to the text field when the user clicks on it.
    uri.setOnFocusChangeListener(this);

    // Populate views from an existing SearchClient.Settings object, if it was passed in the arguments bundle.
    if (savedInstanceState == null && getArguments() != null
            && getArguments().containsKey(BUNDLE_ID_SETTINGS)) {
        // Get the SearchClient.Settings object from this fragment's arguments bundle.
        SearchClient.Settings settings = getArguments().getParcelable(BUNDLE_ID_SETTINGS);

        // Populate subviews with content.
        if (settings != null) {
            name.setText(settings.getName());
            uri.setText(settings.getEndpoint());
            username.setText(settings.getUsername());
            passphrase.setText(settings.getPassword());
        }
    }

    // Dismiss dropdown when the view is first shown.
    name.dismissDropDown();

    // Create the AlertDialog object.
    final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setView(view)
            .setTitle(rowId == -1 ? R.string.dialog_title_addService : R.string.dialog_title_editService)
            .setPositiveButton(R.string.ok, null)
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Dismiss dialog without saving changes.
                    dismiss();
                }
            }).create();

    // Use OnShowListener to override positive button behaviour.
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            // OnShowListener here is used as a hack to override Android Dialog's default OnClickListener
            // that doesn't provide a way to prevent the dialog from getting dismissed when a button is clicked.
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                    .setOnClickListener(EditAPISettingDialogFragment.this);
        }
    });

    return alertDialog;
}

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

public void onSaveCalibration() {
    final Context context = this;
    final MainApp mainApp = (MainApp) this.getApplicationContext();

    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    final EditText input = new EditText(context);
    input.setInputType(InputType.TYPE_CLASS_TEXT);
    input.setFilters(new InputFilter[] { new InputFilter.LengthFilter(22) });

    alertDialogBuilder.setView(input);/*www .  ja  v  a2s .c o m*/
    alertDialogBuilder.setCancelable(false);

    alertDialogBuilder.setTitle(R.string.saveCalibration);
    alertDialogBuilder.setMessage(R.string.giveNameForCalibration);

    alertDialogBuilder.setPositiveButton(R.string.ok, null);
    alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int i) {
            closeKeyboard(input);
            dialog.cancel();
        }
    });
    final AlertDialog alertDialog = alertDialogBuilder.create(); //create the box

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {

            Button b = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

                    if (!input.getText().toString().trim().isEmpty()) {
                        final ArrayList<String> exportList = new ArrayList<String>();

                        for (ColorInfo aColorList : mainApp.colorList) {
                            exportList.add(ColorUtils.getColorRgbString(aColorList.getColor()));
                        }

                        File external = Environment.getExternalStorageDirectory();
                        final String path = external.getPath() + Config.CALIBRATE_FOLDER_NAME;

                        File file = new File(path + input.getText());
                        if (file.exists()) {
                            AlertUtils.askQuestion(context, R.string.overwriteFile, R.string.nameAlreadyExists,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            FileUtils.saveToFile(path, input.getText().toString(),
                                                    exportList.toString());
                                        }
                                    });
                        } else {
                            FileUtils.saveToFile(path, input.getText().toString(), exportList.toString());
                        }

                        closeKeyboard(input);
                        alertDialog.dismiss();
                    } else {
                        input.setError(getString(R.string.invalidName));
                    }
                }
            });
        }
    });

    input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                    || (actionId == EditorInfo.IME_ACTION_DONE)) {

            }
            return false;
        }
    });

    alertDialog.show();
    input.requestFocus();
    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

}