Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

validation - Android: Dialog dismisses without calling dismiss

I have a dialog which performs some validation (below). Thee problem is, the dialog is dismissed after the Toast is displayed, without me calling dismiss. I need to show the toast and keep the dialog open to correct the error.

final EditText txtName = new EditText(this);
AlertDialog.Builder dlgAdd = new AlertDialog.Builder(this)
    .setTitle(R.string.create_category)
    .setMessage(R.string.name)
    .setView(txtName)
    .setPositiveButton(R.string.ok, new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String newCatName = txtName.getText().toString().trim(); // Converts the value of getText to a string.
            if (newCatName != null && newCatName .length() ==0)
            {  
                Toast.makeText(ManageCategories.this, R.string.err_name_required, 3500).show();

            } else {
                try {
                    boolean alreadyExists = mDatabaseAdapter.getCategoryIDs(newCatName).length > 0;// ids of cats with this name
                    if(alreadyExists) {
                        Toast.makeText(ManageCategories.this, R.string.categoryAlreadyExists, 3500).show();
                    } else {
                        mDatabaseAdapter.addCategory(newCatName);
                    }
                }catch(Exception ex){
                    Toast.makeText(ManageCategories.this, R.string.error+':'+ ex.getLocalizedMessage(), 3500).show();
            }
            }
        }
    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
});
dlgAdd.show();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My guess is that you are not creating and showing dialog as mentioned in the Android docs here http://developer.android.com/guide/topics/ui/dialogs.html using OnCreateDialog functions

Please do as mentioned in the docs and let us know if it still does not work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...