0

我知道它应该是上下文。究竟什么是上下文。通常当我在一个类中创建一个对话框时,我会做这样的事情:

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;
}



}
4

2 回答 2

0

添加到萨米尔的答案

修改您的代码以具有构造函数,该构造函数采用调用类的上下文。

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();

于 2012-06-12T15:17:44.203 回答
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()可以在类的私有 Context 变量中设置的上下文对象popTask,然后在doInBackground()函数中访问它。

于 2012-06-12T15:14:15.063 回答