等待来自对话框的用户输入

等待来自对话框的用户输入

本文介绍了Android:等待来自对话框的用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个显示对话框的方法,等待对话框关闭,然后根据对话框内容返回结果.这可能吗?

I would like to implement a method that displays a dialog, waits until the dialog is dismissed, and then returns a result depending on the dialog contents. Is this possible?

public String getUserInput()
{
    //do something to show dialog
    String input = //get input from dialog
    return input;
}

我实际上是在尝试实现一个具有方法public String getUserInput()"的接口,其中返回的字符串必须通过对话框检索.这在java中很容易做到,在android中似乎不可能?

I am actually trying to implement an interface which has method "public String getUserInput()", where the returned String must be retrieved via dialog. This is easily done in java, seems impossible in android?

根据评论中的要求发布一些示例代码

Posting some sample code as requested in comment

getInput() 必须从后台线程调用(我从AsynchTask 调用它).getInput() 显示一个对话框并调用等待.当在对话框上按下 ok 按钮时,对话框将用户输入设置在成员变量中并调用 notify.当调用 notify 时,getInput() 继续并返回成员变量.

getInput() must be called from a background thread (I call it from an AsynchTask). getInput() displays a dialog and calls wait. When the ok button is pressed on the dialog, the dialog sets the user input in a member variable and calls notify. When notify is called, getInput() continues and returns the member variable.

String m_Input;

public synchronized String getInput()
{
    runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(context);
            //customize alert dialog to allow desired input
            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                          m_Input = alert.getCustomInput();
                          notify();
            }
        });
        alert.show();
        }
    });

    try
    {
         wait();
    }
    catch (InterruptedException e)
    {
    }

    return m_Input;
}

推荐答案

感谢所有反馈,我能够使用后台线程以及 wait() 和 notify() 来解决这个问题.我承认这不是给定范例的最佳想法,但有必要符合我正在使用的库.

Thanks for all the feedback, I was able to solve this using a background thread along with a wait() and notify(). I recognize this isn't the greatest idea for the given paradigm, but it was necessary to conform to a library that I am working with.

这篇关于Android:等待来自对话框的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:46