是的,只是传递Activity
给Asynctask
:
AsyncTask myAsyncTask = new MyTask(this);
然后你会发现里面的元素layout
的Activity
:
public class MyTask extends AsyncTask{ public MyActivity activity; public MyTask(MyActivity a){ this.activity = a; } protected void onPostExecute(String result){ ... ... LinearLayout shw_evnt = (LinearLayout) activity.findViewById(R.id.shwevnt); ... ... } }
像丹尼尔介绍这将是一个不好的做法.
例如:
a)创建接口类.
public interface AsyncResponse { void processFinish(String output); }
b)转到AsyncTask类,并将接口AsyncResponse声明为字段:
public class MyAsyncTask extends AsyncTask{ public AsyncResponse delegate = null; @Override protected void onPostExecute(String result) { delegate.processFinish(result); } }
c)在您的主Activity中,您需要实现接口AsyncResponse.
public class MainActivity implements AsyncResponse{ MyAsyncTask asyncTask =new MyAsyncTask(); @Override public void onCreate(Bundle savedInstanceState) { //this to set delegate/listener back to this class asyncTask.delegate = this; //execute the async task asyncTask.execute(); } //this override the implemented method from asyncTask void processFinish(String output){ //Here you will receive the result fired from async class //of onPostExecute(result) method. LinearLayout shw_evnt = (LinearLayout) findViewById(R.id.shwevnt); } }