【问题标题】:Function with return value uses AlertDialog有返回值的函数使用 AlertDialog
【发布时间】:2013-02-11 13:01:43
【问题描述】:

假设我正在从一个接口(我无法修改)覆盖一个函数

public abstract int getResult();

在这个函数中,我想使用 AlertDialog 询问用户结果应该是什么。所以我的实现应该是这样的:

public int getResult() {
    int result;

    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                result = 1;
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                result = 2;
                break;
            }
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("What is the result?").setPositiveButton("1", dialogClickListener)
        .setNegativeButton("2", dialogClickListener).show();

    return result;
}

显然,由于 AlertDialog 的异步特性,这将不起作用。处理这种情况的正确方法是什么?

【问题讨论】:

    标签: android asynchronous


    【解决方案1】:

    您必须仅在 UI 线程上运行此代码,例如:

    runOnUiThread(new Runnable() {
            public void run() {
                getResult();
            }
        });
    

        public int getResult(){
           runOnUiThread(new Runnable() {
            public void run() {
                // your code
            }
        });
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 2016-05-16
      • 1970-01-01
      • 2015-07-30
      • 2011-06-06
      相关资源
      最近更新 更多