我想实现一个显示对话框的方法,等待对话框关闭,然后根据对话框内容返回结果。这可能吗?
public String getUserInput()
{
//do something to show dialog
String input = //get input from dialog
return input;
}
我实际上是在尝试实现一个具有方法“public String getUserInput()”的接口(interface),其中返回的字符串必须通过对话框检索。这在java中很容易做到,在android中似乎不可能?
编辑:根据评论中的要求发布一些示例代码
getInput()
必须从后台线程调用(我从AsynchTask 调用它)。 getInput() 显示一个对话框并调用等待。当在对话框上按下 ok 按钮时,对话框将用户输入设置在成员变量中并调用 notify。当调用 notify 时,getInput() 继续并返回成员变量。
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;
}
最佳答案
Is this possible?
没有。 Android 中没有阻塞的 UI 模型。一切都是异步的。
更新
针对您对问题本身的一些评论,您无法从后台线程显示 UI。正如我在这个答案中所写,Android 中没有阻塞 UI 模型。只需将代码放入对话框的按钮处理程序中,当对话框被接受时您希望执行该处理程序,例如在 this sample project 中.
关于Android:WAITING来自对话框的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4381296/