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

以下は、AsyncTaskを実行しているアクティビティからコンテキストを送信する2つの方法です。

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

popTaskで、コンテキストを設定できるプライベート変数を作成します。

popTask最初のオプションでは、コンテキストを受け入れるクラスのコンストラクターが必要です。

2番目のオプションでは、関数に意味のあるものを渡さない場合は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 に答える
0

サミールの答えに追加するには

クラスを呼び出すコンテキストをとるコンストラクターを持つようにコードを変更します。

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

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

その後Dialog dialog = new Dialog(context);

呼び出しアクティビティで、この非同期タスクを次のように呼び出します

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

于 2012-06-12T15:17:44.203 に答える