有没有办法在AsyncTask中显示AlertDialog?

时间:2016-08-26 08:29:52

标签: android android-asynctask alertdialog

我想在AsyncTask中显示其他类中的AlertDialog。 例>

public class WardListAsyncTask extends AsyncTask<HashMap<String, String>, String, Object> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(HashMap<String, String>... params) {
      ...
    }

   @Override
    protected void onPostExecute(Object result) {
        ConfirmAlertDialog(ez_WardList.this,"HI?"); 
        //this method is in another Class & I want to use this method another Asynctask also..
    }

和ConfirmAlertDialog是......

    Context g_ctx;
String g_content;
public void ez_ConfirmAlertDialog(Context ctx, String content) {
    this.g_ctx=ctx;
    this.g_content=content;

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(g_ctx, AlertDialog.THEME_HOLO_LIGHT);
            builder.setMessage(g_content).setPositiveButton(getString(R.string.kor_confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(displayWidth / 2, LayoutParams.WRAP_CONTENT);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.rgb(10, 174, 239));

        }
    });

}

我认为g_ctx.class.runonuiThread ...但是我不能调用runonuithread ...

我该如何解决?

2 个答案:

答案 0 :(得分:3)

runOnUhThread方法存在于Activity类中。所以应该将Activity传递给你的班级。 例如:

public class MyClass{


public void ez_ConfirmAlertDialog(Activity activity, String content) {
    this.g_ctx=ctx;
    this.g_content=content;

    if(activity == null){
       return;
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(g_ctx, AlertDialog.THEME_HOLO_LIGHT);
            builder.setMessage(g_content).setPositiveButton(getString(R.string.kor_confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    });

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
            alertDialog.getWindow().setLayout(displayWidth / 2, LayoutParams.WRAP_CONTENT);
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.rgb(10, 174, 239));

        }
    });

}

}

答案 1 :(得分:1)

您可以使用处理程序

在主线程中调用它
    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
             // Your code here
        }
    });