当前位置:  开发笔记 > 编程语言 > 正文

无法在AsyncTask中访问"findViewById"

如何解决《无法在AsyncTask中访问"findViewById"》经验,为你挑选了1个好方法。



1> Jorgesys..:

是的,只是传递ActivityAsynctask:

   AsyncTask myAsyncTask = new MyTask(this);

然后你会发现里面的元素layoutActivity:

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

推荐阅读
地之南_816
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有