【问题标题】:button remains pressed while the Asynctask is being executed执行 Asynctask 时按钮保持按下状态
【发布时间】:2013-07-02 12:35:58
【问题描述】:

我有一个按钮,按下它会执行以下代码:

public void onClick(View v) {
            // TODO Auto-generated method stub
            //progressSpin.setVisibility(View.VISIBLE);
            try {
                data=new WebkioskExtractor().execute(username,password).get();
                System.out.println("Data = "+data);                 
            } catch (Exception e) {
                // TODO Auto-geneorated catch block
                e.printStackTrace();
            }
            //progressSpin.setVisibility(View.GONE);
        }

从代码中可以清楚地看出,我必须等待 AsyncTask 完成,因为我依赖于它返回的数据。问题是,在执行任务时(它从互联网获取一些数据),按钮仍处于按下状态。即使我将创建的进度条设置为可见,它也不会显示。

我该如何解决这个问题?我希望按钮被按下一次,然后进度条应该开始旋转,这没有发生。

【问题讨论】:

    标签: android android-asynctask android-progressbar


    【解决方案1】:

    不要使用get()

    data=new WebkioskExtractor().execute(username,password).get();  // Bad! :(
    
    data=new WebkioskExtractor().execute(username,password);  // Good! :) 
    

    它会阻止UI,这就是为什么您的Button 仍然被按下。这也是您的ProgressBar 没有出现的原因(它也在UI 上运行)。我假设你在onPreExecute()dismiss() 中开始你的ProgressBaronPostExecute() 中的AsyncTask。如果没有,这就是你应该做的。如果您的AsyncTask 中的其他所有内容都设置正确,那么删除.get() 应该可以解决您的问题。

    将您的结果从doInBackground() 返回到onPostExecute(),这应该会给您想要的结果。您还可以在onPostExecute()AsyncTask 的任何其他方法上对UI 执行任何您需要的操作,除了doInBackground()

    进度条

    您无需在ProgressBar 上设置Visibility。看这个例子:

    public class GetUsersTask extends AsyncTask<Void, Void, Void> {
        ProgressDialog progress = ProgressDialog.show(LoginScreen.this, "Downloading Users", "Please wait while users are downloaded");
         // you can create it here
    
        @Override
        protected void onPreExecute()
        {
            // show it here like so
            progress.setCancelable(false);
            progress.isIndeterminate();
            progress.show();
        }
    
        @Override
        protected void onPostExecute(Void result) {
    
                // and dismiss it here
                progress.dismiss();
            }
    
        } 
    
        @Override
        protected void onProgressUpdate(Void... values) {
            // can update the ProgressBar here if you need to
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            ...
             }
    

    使用回调

    如果您需要从AsyncTask 获得一个不是您的Activity 的内部类的结果,那么您可以使用interfacecallBackMore about doing that in this answer

    AsyncTask Docs

    【讨论】:

    • 谢谢。那成功了。顺便说一句,我使用的是thisprogressBar,它与progressDialog 不同,它使用可见性。
    猜你喜欢
    • 1970-01-01
    • 2018-07-27
    • 2020-12-02
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多