2

AsyncTask クラスで findViewById() メソッドを使用したい... onPostExecute() と onPreExecute() を試しましたが、うまくいきません

class Proccess extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... arg0) {
    TextView txt = (TextView) findViewById(R.id.tvResult); // cause error
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        TextView txt = (TextView) findViewById(R.id.tvResult); // cause error
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        TextView txt = (TextView) findViewById(R.id.tvResult); // cause error

    }
}
4

3 に答える 3

2

このようにコードを編集します

class Proccess extends AsyncTask<String, Void, Void>{

@Override
protected Void doInBackground(String... arg0) {

    TextView txt = (TextView) findViewById(R.id.tvResult); // cuse error
    return null; //this should be the last statement otherwise cause unreachable code.
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    TextView txt = (TextView) findViewById(R.id.tvResult); // cuse error
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    TextView txt = (TextView) findViewById(R.id.tvResult); // cuse error

}
}

そして、あなたのProcess クラスはあなたのアクティビティのインナークラスでなければなりません。そうしないと、メソッド findViewById(int) が未定義になります。

于 2013-07-26T06:42:26.873 に答える
0

アクティビティ内のテキストビューへの参照を取得し、データ メンバーとして保存する必要があります。内部の AsyncTask からアクセスできます。

postExecute 内で findViewById を使用することの欠点は、アクティビティの終了後に AsyncTask が終了し、findViewById がアプリをクラッシュさせる可能性があることです。

于 2013-07-26T06:35:10.370 に答える