在ASync类中重写和覆盖

时间:2017-01-04 16:53:33

标签: java android android-asynctask override

我有一个用于各种ASyncTasks的类。有时,我需要根据活动或动作隐藏某些按钮,视图或其他内容。需要可见性集的对象可能会有所不同。

MyAsyncTask

    public class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {

    private ProgressBar mProgressBar;
    public ASynceResponse delegate = null;

        public MyAsyncTask() {
          this.delegate = delegate;
          this.mProgressBar = progressBar;
        }

        @Override
        protected void onPreExecute() {
           mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected JSONObject doInBackground(String... params) {
            return; 
        }

        @Override
        protected void onPostExecute(JSONObject data) {
            mProgressBar.setVisibility(View.GONE);
            delegate.processResults(data);
        }


    public interface ASyncResponse {
        void processResults(JSONObject data);
    }

    }

我通常称之为:

new MyAsyncTask(this, mProgressBar).execute("Something","Something Else",null);

我在Activity中传递了ProgressBar,其中显示了后台操作正在发生。

但我想要更多。我想Overide我的课程onPreExecuteonPostExecute隐藏/显示其他项目。

这可能吗?

但是我试图找到一种方法来覆盖onPreExecute以隐藏任何类型(或多种类型)视图。

这样的事情可能吗?

MyAsyncTask myAsyncTask = new MyAsyncTask(new onPreExecute(
                // hide a view
));

1 个答案:

答案 0 :(得分:1)

您可以使用界面。

public class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {

   private ProgressBar mProgressBar;
   public ASynceResponse delegate = null;

       public MyAsyncTask() {
         this.delegate = delegate;
         this.mProgressBar = progressBar;
       }

       @Override
       protected void onPreExecute() {
          delegate.myOnPreExecute();
          mProgressBar.setVisibility(View.VISIBLE);
       }

       @Override
       protected JSONObject doInBackground(String... params) {
           return; 
       }

       @Override
       protected void onPostExecute(JSONObject data) {
           mProgressBar.setVisibility(View.GONE);
           delegate.processResults(data);
       }


       public interface ASyncResponse {
           void processResults(JSONObject data);
           void myOnPreExecute();
       }

   }
  

演示类示例

class Demo implements ASyncResponse{
      .....
      void processResults(JSONObject data){
      ....
      }
      void myOnPreExecute(){
        // do your stuff for pre execute
      }

   }