什么在对话框构造函数内部

时间:2012-06-12 15:02:56

标签: android android-asynctask android-dialog

我知道它应该是背景。 究竟是什么语境。 通常我在课堂上创建一个对话框 我做这样的事情:

final Dialog dialog = new Dialog(this);

但现在我正在尝试在AsyncTask中创建一个对话框<> 因此我无法做到上述原因AsyncTask显然不是一个上下文。 AsyncTask本身就是一个类,也就是说它现在不是一个子类。

public class popTask extends AsyncTask<Void, Void, String> {

Context con =

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);

    final Dialog dialog = new Dialog(con);
    dialog.setContentView(R.layout.custom);
    dialog.setTitle("New & Hot advertise");

    // set the custom dialog components - text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText("Android custom dialog example!");
    ImageView image = (ImageView) dialog.findViewById(R.id.image);
    image.setImageResource(R.drawable.yoda);

    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    dialog.show();
}


@Override
protected String doInBackground(Void... params) {
    // TODO Auto-generated method stub
    return null;
}



}

2 个答案:

答案 0 :(得分:0)

以下是从执行AsyncTask的活动中发送上下文的两种方法:

popTask pTask = new popTask(mContext); //OR
pTask.execute(mContext);

popTask中创建一个私人变量,您可以在其中设置上下文。

在第一个选项中,您需要为您正在接受上下文的类popTask创建一个构造函数。

对于第二个选项,如果您没有向函数doInBackground()传递任何有意义的内容,则可以更改以下行:

public class popTask extends AsyncTask<Object, Void, String>

protected Object doInBackground(Object... params) {
this.mContext = (Context) params[0];

}

您将收到doInBackground()中的上下文对象,您可以在popTask类的私有Context变量中设置该对象,然后在doInBackground()函数中访问它。

答案 1 :(得分:0)

添加到Samir的答案

修改代码,使其具有构造函数,该构造函数接受调用类的上下文。

public class popTask extends AsyncTask<Void, Void, String> {

    private Context context;
    public popTask(Context context)
    {
        this.cotext=context;
    }

然后Dialog dialog = new Dialog(context);

在你的调用活动中,像这样调用这个Asynctask

new popTask(ActivityName.this).execute();

相关问题