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:no.digipost.android.gui.content.UploadActivity.java

private void promtUpload(final File file) {
    final AlertDialog dialog = DialogUtitities
            .getAlertDialogBuilderWithMessageAndTitle(this,
                    getString(R.string.upload_dialog) + file.getName() + "?", getString(R.string.upload))
            .setPositiveButton(R.string.upload, new DialogInterface.OnClickListener() {
                @Override// w w  w  .  j a  v  a  2  s.  c  o  m
                public void onClick(DialogInterface dialogInterface, int i) {
                    executeUploadTask(file);
                    dialogInterface.dismiss();
                }
            }).setNegativeButton(R.string.abort, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                }
            }).create();

    dialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialogInterface) {

            Button b = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    previewFile(file);
                }
            });
        }
    });

    dialog.show();
}

From source file:de.baumann.hhsmoodle.data_subjects.Subjects_Fragment.java

private void setSubjectsList() {

    final helper_main.Item[] items = {
            new helper_main.Item(getString(R.string.subjects_color_red), R.drawable.circle_red),
            new helper_main.Item(getString(R.string.subjects_color_pink), R.drawable.circle_pink),
            new helper_main.Item(getString(R.string.subjects_color_purple), R.drawable.circle_purple),
            new helper_main.Item(getString(R.string.subjects_color_blue), R.drawable.circle_blue),
            new helper_main.Item(getString(R.string.subjects_color_teal), R.drawable.circle_teal),
            new helper_main.Item(getString(R.string.subjects_color_green), R.drawable.circle_green),
            new helper_main.Item(getString(R.string.subjects_color_lime), R.drawable.circle_lime),
            new helper_main.Item(getString(R.string.subjects_color_yellow), R.drawable.circle_yellow),
            new helper_main.Item(getString(R.string.subjects_color_orange), R.drawable.circle_orange),
            new helper_main.Item(getString(R.string.subjects_color_brown), R.drawable.circle_brown),
            new helper_main.Item(getString(R.string.subjects_color_grey), R.drawable.circle_grey), };

    //display data
    final int layoutstyle = R.layout.list_item_schedule;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.att_notes };
    String[] column = new String[] { "subject_title", "subject_content", "subject_attachment" };
    final Cursor row = db.fetchAllData();
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) {
        @Override/*w ww .j a  v a 2  s. c  o  m*/
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row = (Cursor) lv.getItemAtPosition(position);
            final String _id = row.getString(row.getColumnIndexOrThrow("_id"));
            final String subject_title = row.getString(row.getColumnIndexOrThrow("subject_title"));
            final String subject_content = row.getString(row.getColumnIndexOrThrow("subject_content"));
            final String subject_icon = row.getString(row.getColumnIndexOrThrow("subject_icon"));
            final String subject_attachment = row.getString(row.getColumnIndexOrThrow("subject_attachment"));
            final String subject_creation = row.getString(row.getColumnIndexOrThrow("subject_creation"));

            View v = super.getView(position, convertView, parent);
            ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes);
            Subjects_helper.switchIcon(getActivity(), subject_icon, "subject_color", iv_icon);
            iv_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                            android.R.layout.select_dialog_item, android.R.id.text1, items) {
                        @NonNull
                        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                            //Use super class to create the View
                            View v = super.getView(position, convertView, parent);
                            TextView tv = (TextView) v.findViewById(android.R.id.text1);
                            tv.setTextSize(18);
                            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
                            //Add margin between image and text (support various screen densities)
                            int dp5 = (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                            tv.setCompoundDrawablePadding(dp5);

                            return v;
                        }
                    };

                    new AlertDialog.Builder(getActivity())
                            .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.cancel();
                                }
                            }).setAdapter(adapter, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int item) {
                                    if (item == 0) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "1",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 1) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "2",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 2) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "3",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 3) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "4",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 4) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "5",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 5) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "6",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 6) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "7",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 7) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "8",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 8) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "9",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 9) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "10",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    } else if (item == 10) {
                                        db.update(Integer.parseInt(_id), subject_title, subject_content, "11",
                                                subject_attachment, subject_creation);
                                        setSubjectsList();
                                    }
                                }
                            }).show();
                }
            });

            return v;
        }
    };

    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String subject_title = row2.getString(row2.getColumnIndexOrThrow("subject_title"));
            final String subject_content = row2.getString(row2.getColumnIndexOrThrow("subject_content"));

            final CharSequence[] options = { getString(R.string.courseList_todo),
                    getString(R.string.courseList_note), getString(R.string.courseList_random),
                    getString(R.string.courseList_course), getString(R.string.bookmark_createEvent) };

            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.courseList_random))) {

                                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                        getActivity());
                                View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_entry, null);

                                final EditText edit_title = (EditText) dialogView
                                        .findViewById(R.id.note_title_input);
                                edit_title.setHint(R.string.title_hint);
                                edit_title.setText(subject_title);

                                final EditText edit_cont = (EditText) dialogView
                                        .findViewById(R.id.note_text_input);
                                edit_cont.setHint(R.string.text_hint);

                                builder.setView(dialogView);
                                builder.setTitle(R.string.number_edit_entry);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {

                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final android.app.AlertDialog dialog2 = builder.create();
                                // Display the custom alert dialog on interface
                                dialog2.show();

                                dialog2.getButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE)
                                        .setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                //Do stuff, possibly set wantToCloseDialog to true then...
                                                Random_DbAdapter db = new Random_DbAdapter(getActivity());
                                                db.open();

                                                if (db.isExist(subject_title)) {
                                                    Snackbar.make(edit_title,
                                                            getString(R.string.toast_newTitle),
                                                            Snackbar.LENGTH_LONG).show();
                                                } else {
                                                    String inputTitle = edit_title.getText().toString().trim();
                                                    String inputCont = edit_cont.getText().toString().trim();
                                                    db.insert(inputTitle, inputCont, "", "",
                                                            helper_main.createDate());
                                                    dialog2.cancel();
                                                }
                                            }
                                        });
                                helper_main.showKeyboard(getActivity(), edit_title);
                            }

                            if (options[item].equals(getString(R.string.courseList_note))) {
                                Notes_helper.newNote(getActivity(), subject_title, subject_content, "", "", "",
                                        "");
                            }

                            if (options[item].equals(getString(R.string.courseList_todo))) {
                                Todo_helper.newTodo(getActivity(), subject_title, subject_content,
                                        getActivity().getString(R.string.note_content));
                            }

                            if (options[item].equals(getString(R.string.courseList_course))) {

                                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                        getActivity());
                                View dialogView = View.inflate(getActivity(), R.layout.dialog_edit_entry, null);

                                final EditText edit_title = (EditText) dialogView
                                        .findViewById(R.id.note_title_input);
                                edit_title.setHint(R.string.title_hint);
                                edit_title.setText(subject_title);

                                final EditText edit_cont = (EditText) dialogView
                                        .findViewById(R.id.note_text_input);
                                edit_cont.setHint(R.string.text_hint);

                                builder.setView(dialogView);
                                builder.setTitle(R.string.number_edit_entry);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {

                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final android.app.AlertDialog dialog2 = builder.create();
                                // Display the custom alert dialog on interface
                                dialog2.show();

                                dialog2.getButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE)
                                        .setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                //Do stuff, possibly set wantToCloseDialog to true then...
                                                Courses_DbAdapter db = new Courses_DbAdapter(getActivity());
                                                db.open();

                                                if (db.isExist(subject_title)) {
                                                    Snackbar.make(edit_title,
                                                            getString(R.string.toast_newTitle),
                                                            Snackbar.LENGTH_LONG).show();
                                                } else {
                                                    String inputTitle = edit_title.getText().toString().trim();
                                                    String inputCont = edit_cont.getText().toString().trim();
                                                    db.insert(inputTitle, inputCont, "", "",
                                                            helper_main.createDate());
                                                    dialog2.cancel();
                                                }
                                            }
                                        });
                                helper_main.showKeyboard(getActivity(), edit_title);
                            }

                            if (options[item].equals(getString(R.string.bookmark_createEvent))) {
                                helper_main.createCalendarEvent(getActivity(), subject_title, subject_content);
                            }

                        }
                    }).show();
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String subject_title = row2.getString(row2.getColumnIndexOrThrow("subject_title"));
            final String subject_content = row2.getString(row2.getColumnIndexOrThrow("subject_content"));
            final String subject_icon = row2.getString(row2.getColumnIndexOrThrow("subject_icon"));
            final String subject_attachment = row2.getString(row2.getColumnIndexOrThrow("subject_attachment"));
            final String subject_creation = row2.getString(row2.getColumnIndexOrThrow("subject_creation"));

            final CharSequence[] options = { getString(R.string.number_edit_entry),
                    getString(R.string.subjects_copy), getString(R.string.bookmark_remove_bookmark) };
            new android.app.AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {

                            if (options[item].equals(getString(R.string.number_edit_entry))) {

                                LayoutInflater inflater = getActivity().getLayoutInflater();

                                final ViewGroup nullParent = null;
                                View dialogView = inflater.inflate(R.layout.dialog_edit_subject, nullParent);

                                titleInput = (EditText) dialogView.findViewById(R.id.subject_title_);
                                titleInput.setSelection(titleInput.getText().length());
                                titleInput.setText(subject_title);
                                teacherInput = (EditText) dialogView.findViewById(R.id.subject_teacher);
                                teacherInput.setText(subject_content);
                                roomInput = (EditText) dialogView.findViewById(R.id.subject_room);
                                roomInput.setText(subject_attachment);

                                helper_main.showKeyboard(getActivity(), titleInput);

                                final ImageButton be = (ImageButton) dialogView
                                        .findViewById(R.id.imageButtonPri);
                                assert be != null;
                                Subjects_helper.switchIcon(getActivity(), subject_icon, "subject_color", be);

                                be.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {

                                        ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                                                android.R.layout.select_dialog_item, android.R.id.text1,
                                                items) {
                                            @NonNull
                                            public View getView(int position, View convertView,
                                                    @NonNull ViewGroup parent) {
                                                //Use super class to create the View
                                                View v = super.getView(position, convertView, parent);
                                                TextView tv = (TextView) v.findViewById(android.R.id.text1);
                                                tv.setTextSize(18);
                                                tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon,
                                                        0, 0, 0);
                                                //Add margin between image and text (support various screen densities)
                                                int dp5 = (int) (24 * getActivity().getResources()
                                                        .getDisplayMetrics().density + 0.5f);
                                                tv.setCompoundDrawablePadding(dp5);

                                                return v;
                                            }
                                        };

                                        new android.app.AlertDialog.Builder(getActivity())
                                                .setPositiveButton(R.string.toast_cancel,
                                                        new DialogInterface.OnClickListener() {

                                                            public void onClick(DialogInterface dialog,
                                                                    int whichButton) {
                                                                dialog.cancel();
                                                            }
                                                        })
                                                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int item) {
                                                        if (item == 0) {
                                                            be.setImageResource(R.drawable.circle_red);
                                                            sharedPref.edit().putString("subject_color", "1")
                                                                    .apply();
                                                        } else if (item == 1) {
                                                            be.setImageResource(R.drawable.circle_pink);
                                                            sharedPref.edit().putString("subject_color", "2")
                                                                    .apply();
                                                        } else if (item == 2) {
                                                            be.setImageResource(R.drawable.circle_purple);
                                                            sharedPref.edit().putString("subject_color", "3")
                                                                    .apply();
                                                        } else if (item == 3) {
                                                            be.setImageResource(R.drawable.circle_blue);
                                                            sharedPref.edit().putString("subject_color", "4")
                                                                    .apply();
                                                        } else if (item == 4) {
                                                            be.setImageResource(R.drawable.circle_teal);
                                                            sharedPref.edit().putString("subject_color", "5")
                                                                    .apply();
                                                        } else if (item == 5) {
                                                            be.setImageResource(R.drawable.circle_green);
                                                            sharedPref.edit().putString("subject_color", "6")
                                                                    .apply();
                                                        } else if (item == 6) {
                                                            be.setImageResource(R.drawable.circle_lime);
                                                            sharedPref.edit().putString("subject_color", "7")
                                                                    .apply();
                                                        } else if (item == 7) {
                                                            be.setImageResource(R.drawable.circle_yellow);
                                                            sharedPref.edit().putString("subject_color", "8")
                                                                    .apply();
                                                        } else if (item == 8) {
                                                            be.setImageResource(R.drawable.circle_orange);
                                                            sharedPref.edit().putString("subject_color", "9")
                                                                    .apply();
                                                        } else if (item == 9) {
                                                            be.setImageResource(R.drawable.circle_brown);
                                                            sharedPref.edit().putString("subject_color", "10")
                                                                    .apply();
                                                        } else if (item == 10) {
                                                            be.setImageResource(R.drawable.circle_grey);
                                                            sharedPref.edit().putString("subject_color", "11")
                                                                    .apply();
                                                        }
                                                    }
                                                }).show();
                                    }
                                });

                                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                                        getActivity());
                                builder.setTitle(R.string.subjects_edit);
                                builder.setView(dialogView);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                Subject_DbAdapter db = new Subject_DbAdapter(getActivity());
                                                db.open();

                                                String inputTitle = titleInput.getText().toString().trim();
                                                String inputTeacher = teacherInput.getText().toString().trim();
                                                String inputRoom = roomInput.getText().toString().trim();

                                                db.update(Integer.parseInt(_id), inputTitle, inputTeacher,
                                                        sharedPref.getString("subject_color", ""), inputRoom,
                                                        subject_creation);
                                                dialog.dismiss();
                                                setSubjectsList();
                                                Snackbar.make(lv, R.string.bookmark_added,
                                                        Snackbar.LENGTH_SHORT).show();
                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final android.support.v7.app.AlertDialog dialog2 = builder.create();
                                dialog2.show();
                            }

                            if (options[item].equals(getString(R.string.subjects_copy))) {

                                LayoutInflater inflater = getActivity().getLayoutInflater();

                                final ViewGroup nullParent = null;
                                View dialogView = inflater.inflate(R.layout.dialog_edit_subject, nullParent);

                                titleInput = (EditText) dialogView.findViewById(R.id.subject_title_);
                                titleInput.setSelection(titleInput.getText().length());
                                titleInput.setText(subject_title);
                                teacherInput = (EditText) dialogView.findViewById(R.id.subject_teacher);
                                teacherInput.setText(subject_content);
                                roomInput = (EditText) dialogView.findViewById(R.id.subject_room);
                                roomInput.setText(subject_attachment);

                                helper_main.showKeyboard(getActivity(), titleInput);

                                final ImageButton be = (ImageButton) dialogView
                                        .findViewById(R.id.imageButtonPri);
                                Subjects_helper.switchIcon(getActivity(), subject_icon, "subject_color", be);

                                be.setOnClickListener(new View.OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {

                                        ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                                                android.R.layout.select_dialog_item, android.R.id.text1,
                                                items) {
                                            @NonNull
                                            public View getView(int position, View convertView,
                                                    @NonNull ViewGroup parent) {
                                                //Use super class to create the View
                                                View v = super.getView(position, convertView, parent);
                                                TextView tv = (TextView) v.findViewById(android.R.id.text1);
                                                tv.setTextSize(18);
                                                tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon,
                                                        0, 0, 0);
                                                //Add margin between image and text (support various screen densities)
                                                int dp5 = (int) (24 * getActivity().getResources()
                                                        .getDisplayMetrics().density + 0.5f);
                                                tv.setCompoundDrawablePadding(dp5);

                                                return v;
                                            }
                                        };

                                        new android.app.AlertDialog.Builder(getActivity())
                                                .setPositiveButton(R.string.toast_cancel,
                                                        new DialogInterface.OnClickListener() {

                                                            public void onClick(DialogInterface dialog,
                                                                    int whichButton) {
                                                                dialog.cancel();
                                                            }
                                                        })
                                                .setAdapter(adapter, new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int item) {
                                                        if (item == 0) {
                                                            be.setImageResource(R.drawable.circle_red);
                                                            sharedPref.edit().putString("subject_color", "1")
                                                                    .apply();
                                                        } else if (item == 1) {
                                                            be.setImageResource(R.drawable.circle_pink);
                                                            sharedPref.edit().putString("subject_color", "2")
                                                                    .apply();
                                                        } else if (item == 2) {
                                                            be.setImageResource(R.drawable.circle_purple);
                                                            sharedPref.edit().putString("subject_color", "3")
                                                                    .apply();
                                                        } else if (item == 3) {
                                                            be.setImageResource(R.drawable.circle_blue);
                                                            sharedPref.edit().putString("subject_color", "4")
                                                                    .apply();
                                                        } else if (item == 4) {
                                                            be.setImageResource(R.drawable.circle_teal);
                                                            sharedPref.edit().putString("subject_color", "5")
                                                                    .apply();
                                                        } else if (item == 5) {
                                                            be.setImageResource(R.drawable.circle_green);
                                                            sharedPref.edit().putString("subject_color", "6")
                                                                    .apply();
                                                        } else if (item == 6) {
                                                            be.setImageResource(R.drawable.circle_lime);
                                                            sharedPref.edit().putString("subject_color", "7")
                                                                    .apply();
                                                        } else if (item == 7) {
                                                            be.setImageResource(R.drawable.circle_yellow);
                                                            sharedPref.edit().putString("subject_color", "8")
                                                                    .apply();
                                                        } else if (item == 8) {
                                                            be.setImageResource(R.drawable.circle_orange);
                                                            sharedPref.edit().putString("subject_color", "9")
                                                                    .apply();
                                                        } else if (item == 9) {
                                                            be.setImageResource(R.drawable.circle_brown);
                                                            sharedPref.edit().putString("subject_color", "10")
                                                                    .apply();
                                                        } else if (item == 10) {
                                                            be.setImageResource(R.drawable.circle_grey);
                                                            sharedPref.edit().putString("subject_color", "11")
                                                                    .apply();
                                                        }
                                                    }
                                                }).show();
                                    }
                                });

                                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                                        getActivity());
                                builder.setTitle(R.string.subjects_edit);
                                builder.setView(dialogView);
                                builder.setPositiveButton(R.string.toast_yes,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                Subject_DbAdapter db = new Subject_DbAdapter(getActivity());
                                                db.open();

                                                String inputTitle = titleInput.getText().toString().trim();
                                                String inputTeacher = teacherInput.getText().toString().trim();
                                                String inputRoom = roomInput.getText().toString().trim();

                                                Date date = new Date();
                                                DateFormat dateFormat = new SimpleDateFormat(
                                                        "yy-MM-dd_HH-mm-ss", Locale.getDefault());
                                                String creation = dateFormat.format(date);

                                                if (db.isExist(creation)) {
                                                    Snackbar.make(titleInput,
                                                            getString(R.string.toast_newTitle),
                                                            Snackbar.LENGTH_LONG).show();
                                                } else {
                                                    db.insert(inputTitle, inputTeacher,
                                                            sharedPref.getString("subject_color", creation),
                                                            inputRoom, helper_main.createDate());
                                                    dialog.dismiss();
                                                    setSubjectsList();
                                                }

                                            }
                                        });
                                builder.setNegativeButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        });

                                final android.support.v7.app.AlertDialog dialog2 = builder.create();
                                dialog2.show();
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {

                                Snackbar snackbar = Snackbar
                                        .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.delete(Integer.parseInt(_id));
                                                setSubjectsList();
                                            }
                                        });
                                snackbar.show();
                            }

                        }
                    }).show();

            return true;
        }
    });
}

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

@Override
public void onEscortClosed(Escort escort) {
    AlertDialog alertDialog = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
            .setTitle(reporter.getName().split(" ")[0] + " telah sampai.")
            .setMessage(reporter.getName().split(" ")[0]
                    + " telah sampai pada tujuan dengan selamat, terimakasih atas partisipasi anda.")
            .setPositiveButton("OK", (dialog, which) -> {
                showLoading();/*from w w  w.  j  av a 2 s .  c  o  m*/
                User currentUser = CacheManager.pluck().getCurrentUser();
                Map<String, Object> data = new HashMap<>();
                data.put("users/" + currentUser.getUserId() + "/status/", "SIAP");
                FirebaseApi.pluck().getApi().updateChildren(data, (firebaseError, firebase) -> {
                    if (firebaseError != null) {
                        Timber.e(firebaseError.getMessage());
                        showError("Gagal mengirimkan data konfirmasi!");
                        dismissLoading();
                    } else {
                        currentUser.setStatus(User.Status.SIAP);
                        CacheManager.pluck().cacheCurrentUser(currentUser);
                        StateManager.pluck().setState(StateManager.pluck().recoveryState());
                        Intent intent = new Intent(this, TombolActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        dismissLoading();
                    }
                });
                dialog.dismiss();
            }).setCancelable(false).show();

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

From source file:org.telegram.ui.ThemeActivity.java

private void openThemeCreate() {
    final EditTextBoldCursor editText = new EditTextBoldCursor(getParentActivity());
    editText.setBackgroundDrawable(Theme.createEditTextDrawable(getParentActivity(), true));

    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
    builder.setTitle(LocaleController.getString("NewTheme", R.string.NewTheme));
    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialog, which) -> {

    });//from   w w w.j a v a 2 s  .com

    LinearLayout linearLayout = new LinearLayout(getParentActivity());
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    builder.setView(linearLayout);

    final TextView message = new TextView(getParentActivity());
    message.setText(LocaleController.formatString("EnterThemeName", R.string.EnterThemeName));
    message.setTextSize(16);
    message.setPadding(AndroidUtilities.dp(23), AndroidUtilities.dp(12), AndroidUtilities.dp(23),
            AndroidUtilities.dp(6));
    message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
    linearLayout.addView(message,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
    editText.setMaxLines(1);
    editText.setLines(1);
    editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
    editText.setGravity(Gravity.LEFT | Gravity.TOP);
    editText.setSingleLine(true);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
    editText.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setCursorSize(AndroidUtilities.dp(20));
    editText.setCursorWidth(1.5f);
    editText.setPadding(0, AndroidUtilities.dp(4), 0, 0);
    linearLayout.addView(editText,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, Gravity.TOP | Gravity.LEFT, 24, 6, 24, 0));
    editText.setOnEditorActionListener((textView, i, keyEvent) -> {
        AndroidUtilities.hideKeyboard(textView);
        return false;
    });
    final AlertDialog alertDialog = builder.create();
    alertDialog.setOnShowListener(dialog -> AndroidUtilities.runOnUIThread(() -> {
        editText.requestFocus();
        AndroidUtilities.showKeyboard(editText);
    }));
    showDialog(alertDialog);
    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
        if (editText.length() == 0) {
            Vibrator vibrator = (Vibrator) ApplicationLoader.applicationContext
                    .getSystemService(Context.VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(200);
            }
            AndroidUtilities.shakeView(editText, 2, 0);
            return;
        }
        ThemeEditorView themeEditorView = new ThemeEditorView();
        String name = editText.getText().toString() + ".attheme";
        themeEditorView.show(getParentActivity(), name);
        Theme.saveCurrentTheme(name, true);
        updateRows();
        alertDialog.dismiss();

        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        if (preferences.getBoolean("themehint", false)) {
            return;
        }
        preferences.edit().putBoolean("themehint", true).commit();
        try {
            Toast.makeText(getParentActivity(),
                    LocaleController.getString("CreateNewThemeHelp", R.string.CreateNewThemeHelp),
                    Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            FileLog.e(e);
        }
    });
}

From source file:org.rm3l.ddwrt.mgmt.AbstractRouterMgmtDialogFragment.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

    final AlertDialog d = (AlertDialog) getDialog();
    if (d != null) {

        d.findViewById(R.id.router_add_privkey).setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override/*w  w w.j  a v  a  2s.c  o m*/
            public void onClick(View view) {
                //Open up file picker

                // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
                // browser.
                final Intent intent = new Intent();

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                } else {
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                }

                // Filter to only show results that can be "opened", such as a
                // file (as opposed to a list of contacts or timezones)
                intent.addCategory(Intent.CATEGORY_OPENABLE);

                // search for all documents available via installed storage providers
                intent.setType("*/*");

                AbstractRouterMgmtDialogFragment.this.startActivityForResult(intent, READ_REQUEST_CODE);
            }
        });

        d.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Validate form
                boolean validForm = validateForm(d);

                if (validForm) {
                    // Now check actual connection to router ...
                    new CheckRouterConnectionAsyncTask(
                            ((EditText) d.findViewById(R.id.router_add_ip)).getText().toString(),
                            getSherlockActivity()
                                    .getSharedPreferences(DEFAULT_SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE)
                                    .getBoolean(ALWAYS_CHECK_CONNECTION_PREF_KEY, true)).execute(d);
                }
                ///else dialog stays open. 'Cancel' button can still close it.
            }
        });
    }
}

From source file:com.abhijitvalluri.android.fitnotifications.TimePickerFragment.java

@Override
@NonNull//ww  w  .j  a  v  a2s .  com
public Dialog onCreateDialog(Bundle savedInstanceState) {
    int hour = getArguments().getInt(ARG_HOUR);
    int minute = getArguments().getInt(ARG_MINUTE);
    mOtherHour = getArguments().getInt(ARG_OTHER_HOUR);
    mOtherMinute = getArguments().getInt(ARG_OTHER_MINUTE);
    mOtherTimeFormatted = DateFormat.getTimeFormat(getActivity())
            .format(Func.convertHourMinute2Date(mOtherHour, mOtherMinute));
    mRequestCode = getArguments().getInt(ARG_REQUEST_CODE);

    View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_time, null);

    mTimePicker = (TimePicker) v.findViewById(R.id.dialog_time_time_picker);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        mTimePicker.setHour(hour);
        mTimePicker.setMinute(minute);
    } else {
        //noinspection deprecation
        mTimePicker.setCurrentHour(hour);
        //noinspection deprecation
        mTimePicker.setCurrentMinute(minute);
    }
    mTimePicker.setIs24HourView(DateFormat.is24HourFormat(getActivity()));

    @StringRes
    int titleStringId = mRequestCode == AppSettingsActivity.START_TIME_REQUEST ? R.string.start_time_heading
            : R.string.stop_time_heading;

    final AlertDialog dialog = new AlertDialog.Builder(getActivity()).setView(v).setTitle(titleStringId)
            .setNegativeButton(android.R.string.cancel, null)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int hour, minute;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        hour = mTimePicker.getHour();
                        minute = mTimePicker.getMinute();
                    } else {
                        //noinspection deprecation
                        hour = mTimePicker.getCurrentHour();
                        //noinspection deprecation
                        minute = mTimePicker.getCurrentMinute();
                    }
                    sendResult(mRequestCode, hour, minute);
                }
            }).create();

    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            int hour, minute;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                hour = mTimePicker.getHour();
                minute = mTimePicker.getMinute();
            } else {
                //noinspection deprecation
                hour = mTimePicker.getCurrentHour();
                //noinspection deprecation
                minute = mTimePicker.getCurrentMinute();
            }
            Button positiveButton = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
            sanityCheckTimeChoice(positiveButton, hour, minute);
        }
    });

    mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
            Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);

            sanityCheckTimeChoice(positiveButton, hourOfDay, minute);
        }
    });

    return dialog;
}

From source file:edu.rutgers.winlab.crowdpp.ui.HomeFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.home_fragment_layout, container, false);

    tb_cal = (ToggleButton) view.findViewById(R.id.tb_home_calibration);
    tb_service = (ToggleButton) view.findViewById(R.id.tb_home_service);
    tb_test = (ToggleButton) view.findViewById(R.id.tb_home_test);
    tv_cal_content = (TextView) view.findViewById(R.id.tv_home_calibration_content);
    tv_cal_text = (TextView) view.findViewById(R.id.tv_home_calibration_text);
    tv_debug = (TextView) view.findViewById(R.id.tv_home_test_debug);
    tv_record = (TextView) view.findViewById(R.id.tv_home_test_record);
    timer_cal = (Chronometer) view.findViewById(R.id.timer_calibration);
    timer_test = (Chronometer) view.findViewById(R.id.timer_test);
    rl_service = (RelativeLayout) view.findViewById(R.id.rl_home_service);
    rl_test = (RelativeLayout) view.findViewById(R.id.rl_home_test);
    if (isMyServiceRunning() == true)
        tb_service.setChecked(true);//w  w  w.  j  av a2 s.  c  o  m

    if (Constants.calibration())
        tv_cal_content.setText("You are all set for the calibration.");

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Toast.makeText(getActivity(), "Can not find SD card ...", Toast.LENGTH_SHORT).show();
        getActivity().finish();
    }

    crowdppDir = new File(Constants.crowdppPath);
    if (!crowdppDir.exists() || !crowdppDir.isDirectory()) {
        crowdppDir.mkdir();
    }

    testDir = new File(Constants.testPath);
    if (!testDir.exists() || !testDir.isDirectory()) {
        testDir.mkdir();
    }

    calWavFile = crowdppDir + "/" + Constants.PHONE_ID + ".wav";

    timer_cal.setVisibility(View.INVISIBLE);
    timer_test.setVisibility(View.INVISIBLE);

    mDatabase = new DataBaseHelper(getActivity().getApplicationContext());
    mDB = mDatabase.getWritableDatabase();

    gps = new LocationTracker(getActivity().getApplicationContext());

    s3Client = new AmazonS3Client(new BasicAWSCredentials(Constants.ACCESS_KEY_ID, Constants.SECRET_KEY));
    s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));

    tb_cal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // prevent the calibration button being pressed when either and test or service is running 
            if (tb_service.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the service...", Toast.LENGTH_SHORT).show();
                tb_cal.setChecked(false);
            } else if (tb_test.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the test...", Toast.LENGTH_SHORT).show();
                tb_cal.setChecked(false);
            }
            // calibration
            else {
                if (isChecked) {
                    tv_cal_text.setText(Constants.cal_text);
                    rl_service.setVisibility(View.INVISIBLE);
                    rl_test.setVisibility(View.INVISIBLE);
                    timer_cal.setVisibility(View.VISIBLE);

                    AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
                    dialog.setTitle("Calibration");
                    dialog.setMessage(Constants.cal_dialog);
                    dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            timer_cal.setBase(SystemClock.elapsedRealtime());
                            timer_cal.start();
                            tv_cal_content.setText("Recording your voice...");

                            Bundle mbundle = new Bundle();
                            mbundle.putString("audiopath", calWavFile);
                            Log.i("HomeFragment", "start audio recording service");

                            // delete the existing calibration data before the recalibration 
                            FileProcess.deleteFile(calWavFile);
                            FileProcess.deleteFile(calWavFile + ".jstk.mfcc.txt");
                            FileProcess.deleteFile(calWavFile + ".YIN.pitch.txt");

                            // start audio recording
                            Intent recordIntent = new Intent(getActivity(), AudioRecordService.class);
                            recordIntent.putExtras(mbundle);
                            getActivity().startService(recordIntent);
                        }
                    });
                    dialog.show();
                    dialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextSize(20);
                } else {
                    // stop audio recording
                    Intent recordIntent = new Intent(getActivity(), AudioRecordService.class);
                    getActivity().stopService(recordIntent);
                    timer_cal.stop();
                    tb_cal.setClickable(false);
                    tv_cal_content.setText("Calibrating....");
                    // start calibration
                    new Calibration().execute();
                    tb_cal.setClickable(true);
                    tv_cal_text.setText("");
                    rl_service.setVisibility(View.VISIBLE);
                    rl_test.setVisibility(View.VISIBLE);
                    timer_cal.setVisibility(View.INVISIBLE);
                }
            }
        }
    });

    tb_service.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // prevent the service button being pressed when either and test or calibration is running           
            if (tb_cal.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the calibration...", Toast.LENGTH_SHORT).show();
                tb_service.setChecked(false);
            } else if (tb_test.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the test...", Toast.LENGTH_SHORT).show();
                tb_service.setChecked(false);
            }
            // speaker counting service
            else {
                Intent countIntent = new Intent(getActivity(), SpeakerCountService.class);
                if (isChecked) {
                    getActivity().startService(countIntent);
                } else {
                    getActivity().stopService(countIntent);
                }
            }
        }
    });

    tb_test.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // prevent the test button being pressed when either and service or calibration is running           
            if (tb_cal.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the calibration...", Toast.LENGTH_SHORT).show();
                tb_test.setChecked(false);
            } else if (tb_service.isChecked()) {
                Toast.makeText(getActivity(), "Please turn off the service...", Toast.LENGTH_SHORT).show();
                tb_test.setChecked(false);
            }
            // perform the speaker counting test
            else {
                if (isChecked) {
                    // get location information
                    gps.getLocation();
                    if (gps.canGetLocation()) {
                        latitude = gps.getLatitude();
                        longitude = gps.getLongitude();
                    } else {
                        latitude = -1;
                        longitude = -1;
                    }
                    gps.stopUsingGPS();

                    timer_test.setBase(SystemClock.elapsedRealtime());
                    timer_test.start();
                    tv_debug.setText("Recording...");
                    testWavFile = testDir + "/" + FileProcess.newFileOnTime("wav");
                    // start audio recording
                    Bundle mbundle = new Bundle();
                    mbundle.putString("audiopath", testWavFile);
                    Log.i("HomeFragment", "start audio recording service");
                    Intent recordIntent = new Intent(getActivity(), AudioRecordService.class);
                    recordIntent.putExtras(mbundle);
                    date = Now.getDate();
                    start = Now.getTimeOfDay();
                    getActivity().startService(recordIntent);
                    timer_test.setVisibility(View.VISIBLE);
                } else {
                    // stop audio recording
                    Intent recordIntent = new Intent(getActivity(), AudioRecordService.class);
                    getActivity().stopService(recordIntent);
                    timer_test.stop();
                    end = Now.getTimeOfDay();
                    tb_test.setClickable(false);
                    // start speaker counting test
                    new Test().execute();
                    timer_test.setVisibility(View.INVISIBLE);
                    tb_test.setClickable(true);
                }
            }
        }
    });
    return view;
}

From source file:com.chaitu.lmscalendar.ui.UrlDialog.java

@Override
public void onStart() {
    super.onStart();
    final AlertDialog dlg = (AlertDialog) getDialog();
    if (dlg == null)
        return;/* www  .  jav  a2 s  .c o  m*/

    View.OnClickListener onClickTask;
    onClickTask = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String url = mTextCalendarUrl.getText().toString();
            String username = mTextUsername.getText().toString();
            String password = mTextPassword.getText().toString();
            String calendar = mTextPassword.getText().toString();
            long sync_interval = mSpinnerSyncInterval.getSelectedItemId();
            CalendarModel calendarModel = (CalendarModel) mSpinnerCalendar.getSelectedItem();
            int calID = calendarModel.getId();
            String calName = calendarModel.getName();

            /*if (!mActivity.setSource(url, null, username, password)) {
            TextView label = (TextView) dlg.findViewById(R.id.TextViewUrlError);
            label.setText(R.string.invalid_url);
            return;
            }*/

            Intent intent = new Intent(getActivity(), AlarmReceiver.class);
            intent.putExtra(AlarmReceiver.ACTION_ALARM, AlarmReceiver.ACTION_ALARM);
            final PendingIntent pIntent = PendingIntent.getBroadcast(getActivity(), 1234567, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarms = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            alarms.cancel(pIntent);

            Settings settings = mActivity.getSettings();
            settings.putString(Settings.PREF_LASTURL, url);

            settings.putString(Settings.PREF_LASTURLUSERNAME, username);
            settings.putString(Settings.PREF_LASTURLPASSWORD, password);
            settings.putString(Settings.PREF_LASTCALENDARNAME, calName);
            settings.putInt(Settings.PREF_LASTCALENDARID, calID);
            settings.putInt(Settings.PREF_LASTSYNCINTERVAL, (int) sync_interval);
            mActivity.startIntent();
            dlg.dismiss();

        }
    };

    dlg.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(onClickTask);

}

From source file:group.pals.android.lib.ui.filechooser.FragmentFiles.java

/**
 * Confirms user to create new directory.
 *//*ww  w .  j a v a 2s.c o m*/
private void showNewDirectoryCreationDialog() {
    final AlertDialog dialog = Dlg.newAlertDlg(getActivity());

    View view = getLayoutInflater(null).inflate(R.layout.afc_simple_text_input_view, null);
    final EditText textFile = (EditText) view.findViewById(R.id.afc_text1);
    textFile.setHint(R.string.afc_hint_folder_name);
    textFile.setOnEditorActionListener(new TextView.OnEditorActionListener() {

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

    dialog.setView(view);
    dialog.setTitle(R.string.afc_cmd_new_folder);
    dialog.setIcon(android.R.drawable.ic_menu_add);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    final String name = textFile.getText().toString().trim();
                    if (!FileUtils.isFilenameValid(name)) {
                        Dlg.toast(getActivity(), getString(R.string.afc_pmsg_filename_is_invalid, name),
                                Dlg.LENGTH_SHORT);
                        return;
                    }

                    new LoadingDialog<Void, Void, Uri>(getActivity(), false) {

                        @Override
                        protected Uri doInBackground(Void... params) {
                            return getActivity().getContentResolver().insert(
                                    BaseFile.genContentUriBase(getCurrentLocation().getAuthority()).buildUpon()
                                            .appendPath(getCurrentLocation().getLastPathSegment())
                                            .appendQueryParameter(BaseFile.PARAM_NAME, name)
                                            .appendQueryParameter(BaseFile.PARAM_FILE_TYPE,
                                                    Integer.toString(BaseFile.FILE_TYPE_DIRECTORY))
                                            .build(),
                                    null);
                        }// doInBackground()

                        @Override
                        protected void onPostExecute(Uri result) {
                            super.onPostExecute(result);

                            if (result != null) {
                                Dlg.toast(getActivity(), getString(R.string.afc_msg_done), Dlg.LENGTH_SHORT);
                            } else
                                Dlg.toast(getActivity(),
                                        getString(R.string.afc_pmsg_cannot_create_folder, name),
                                        Dlg.LENGTH_SHORT);
                        }// onPostExecute()

                    }.execute();
                }// onClick()
            });
    dialog.show();
    Ui.showSoftKeyboard(textFile, true);

    final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    buttonOk.setEnabled(false);

    textFile.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            /*
             * Do nothing.
             */
        }// onTextChanged()

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            /*
             * Do nothing.
             */
        }// beforeTextChanged()

        @Override
        public void afterTextChanged(Editable s) {
            buttonOk.setEnabled(FileUtils.isFilenameValid(s.toString().trim()));
        }// afterTextChanged()
    });
}

From source file:com.haibison.android.anhuu.FragmentFiles.java

/**
 * Confirms user to create new directory.
 *//* w  ww  .  j  av a 2  s. c om*/
private void showNewDirectoryCreationDialog() {
    final AlertDialog dialog = Dlg.newAlertDlg(getActivity());

    View view = getLayoutInflater(null).inflate(R.layout.anhuu_f5be488d_simple_text_input_view, null);
    final EditText textFile = (EditText) view.findViewById(R.id.anhuu_f5be488d_text1);
    textFile.setHint(R.string.anhuu_f5be488d_hint_folder_name);
    textFile.setOnEditorActionListener(new TextView.OnEditorActionListener() {

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

    dialog.setView(view);
    dialog.setTitle(R.string.anhuu_f5be488d_cmd_new_folder);
    dialog.setIcon(android.R.drawable.ic_menu_add);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(android.R.string.ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    final String name = textFile.getText().toString().trim();
                    if (!FileUtils.isFilenameValid(name)) {
                        Dlg.toast(getActivity(),
                                getString(R.string.anhuu_f5be488d_pmsg_filename_is_invalid, name),
                                Dlg.LENGTH_SHORT);
                        return;
                    }

                    new LoadingDialog<Void, Void, Uri>(getActivity(), false) {

                        @Override
                        protected Uri doInBackground(Void... params) {
                            return getActivity().getContentResolver().insert(
                                    BaseFile.genContentUriBase(getCurrentLocation().getAuthority()).buildUpon()
                                            .appendPath(getCurrentLocation().getLastPathSegment())
                                            .appendQueryParameter(BaseFile.PARAM_NAME, name)
                                            .appendQueryParameter(BaseFile.PARAM_FILE_TYPE,
                                                    Integer.toString(BaseFile.FILE_TYPE_DIRECTORY))
                                            .build(),
                                    null);
                        }// doInBackground()

                        @Override
                        protected void onPostExecute(Uri result) {
                            super.onPostExecute(result);

                            if (result != null) {
                                Dlg.toast(getActivity(), getString(R.string.anhuu_f5be488d_msg_done),
                                        Dlg.LENGTH_SHORT);
                            } else
                                Dlg.toast(getActivity(),
                                        getString(R.string.anhuu_f5be488d_pmsg_cannot_create_folder, name),
                                        Dlg.LENGTH_SHORT);
                        }// onPostExecute()

                    }.execute();
                }// onClick()
            });
    dialog.show();
    UI.showSoftKeyboard(textFile, true);

    final Button buttonOk = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    buttonOk.setEnabled(false);

    textFile.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            /*
             * Do nothing.
             */
        }// onTextChanged()

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            /*
             * Do nothing.
             */
        }// beforeTextChanged()

        @Override
        public void afterTextChanged(Editable s) {
            buttonOk.setEnabled(FileUtils.isFilenameValid(s.toString().trim()));
        }// afterTextChanged()
    });
}