警告对话框弹出较晚

3

/*我遇到了一个奇怪的问题,在OnMenuItemClickListener内,我调用了一个自己制作的警告对话框,但是似乎当我调用警告对话框时,并没有在正确的时刻显示出来,而是在onMenuItemClick完成之后才显示。我做错了什么?*/

class MyListMenuListener implements OnMenuItemClickListener
    {

        private String TAG;

        @Override
        public boolean onMenuItemClick(MenuItem item)
        {
            if (item.getItemId() == saveRoute.getItemId())
            {                   
                alertDialogSaveFile();
                //nameInput = "testone.txt";
                //some operations
//                                      ...
 //                                      return true;
            }

// ...

/*the wierd thing is that the alert dialog doesnt show up on the same moment i call it..
only after the onMenuItemClick operation ends (with return)
and this is how my alertdialog looks like:*/

        private void alertDialogSaveFile()
{

AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Save your current map");
        alert.setMessage("Please insert name for this route");
        final EditText saveNameInput = new EditText(TwittListActivity.this);

        alert.setView(saveNameInput);
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                nameInput = saveNameInput.getText().toString();
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
            }
        });
         AlertDialog ad = alert.create();
         ad.show();
    }


//Thanks!
//ray.

我理解你的意思,但这样做不太合乎逻辑,也不是“整洁”的编码方式。难道没有其他方法,可以将所有内容都放在okClick函数内部吗? - rayman
1个回答

3

在Android中,对话框不是同步的,因此很可能UI线程在创建/显示对话框之前就已经完成了onMenuItemClick()方法(对话框由封闭的Activity管理)。

编辑:我误解了你问题的一部分。将alertDialogSaveFile()方法保留在原处,并将实际保存文件的代码放入onClick()处理程序中。由于Android中的对话框不是同步的,因此您需要在对话框回调本身中执行保存操作。无法显示对话框,等待用户响应,然后从对话框获取结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接