从 AlertDialog 返回一个值 [英] Returning A Value From AlertDialog

查看:45
本文介绍了从 AlertDialog 返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个函数来创建一个 AlertDialog 并返回用户输入的字符串,这是我用于创建对话框的函数,我如何返回值?

I want to build a function that creates an AlertDialog and returns the string that the user entered, this the function I have for creating the dialog, how do I return the value?

String m_Text = "";
private String openDialog(String title) {
    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
    builder.setTitle(title);

    final EditText input = new EditText(view.getContext());
    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
    builder.setView(input);

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            m_Text = input.getText().toString();
        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    builder.show();

// return string
} 

推荐答案

打开您的 AlertDialog 的调用 builder.show() 不是阻塞调用,这意味着下一条指令将在不等待 AlertDialog 完成(返回)的情况下执行.您应该与之交互的方式是使用某种回调.例如,您的 OnClickListeners 就是这种模式的实现.

The call builder.show() which opens your AlertDialog is not a blocking call, meaning the next instructions will be executed without waiting for the AlertDialog to finish (return). The way you should interact with it is by using some sort of callback. For instance, your OnClickListeners are an implementation of such a pattern.

实现您想要的一种干净的方法是创建一个函数式接口,它是一个只有一种方法的接口.你会用它来处理你的回调.

One clean way to achieve what you want is to create a Functional Interface which is an interface having only one method. You would use it for handling your callbacks.

interface OnOK{
    void onTextEntered(String text);
}

然后你会改变你的方法:

And then you would alter you method to be like:

private void openDialog(String title, final OnOK onOK) {
    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
    builder.setTitle(title);

    final EditText input = new EditText(view.getContext());
    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
    builder.setView(input);

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialog, int which) {
          //Oi, look at this line!
          onOK.onTextEntered(input.getText().toString());
       }
    });

    builder.show();
} 

你可以这样使用它:

openDialog("Title", new OnOK() {
   @Override
   onTextEntered(String text) {
      Log.i("LOG", text);
   } 
});

这篇关于从 AlertDialog 返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆