【问题标题】:DialogFragment with ProgressBar to update when task updatesDialogFragment 和 ProgressBar 在任务更新时更新
【发布时间】:2016-03-08 16:09:50
【问题描述】:

我有一个 AsyncTask 可以将进度发布到主要活动。

我还有一个带有 ProgressBar 的 DialogFragment,我在我的主要活动中创建了它。

在主活动中,我首先执行 AsyncTask,然后创建 DialogFragment。

processTask = new ProcessImageAsyncTask(dataPathFile, lang, this, tessBaseApi);
processTask.execute(bitmap);

android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
DialogFragment dialog = new TessProgressDialog();
dialog.setCancelable(true);
dialog.show(fragmentManager, "tessProgress");

我想在主要活动收到来自异步任务的更新时更新进度条。有什么想法吗?

【问题讨论】:

    标签: android android-asynctask android-dialogfragment android-progressbar


    【解决方案1】:

    基本上我在写问题时自己找到了解决方案,但我找不到任何其他答案,所以这里是:

    解决方法是在主activity中覆盖onAttachFragment:

    @Override
    public void onAttachFragment(Fragment fragment)
    {
        if (fragment instanceof TessProgressDialog)
        {
            try {
                // Instantiate the NoticeDialogListener so we can send events to the host
                progressListener = (TessProgressUpdaterInterface) fragment;
            } catch (ClassCastException e) {
                // The activity doesn't implement the interface, throw exception
                throw new ClassCastException(fragment.toString()
                        + " must implement NoticeDialogListener");
            }
            super.onAttachFragment(fragment);
        }
    }
    

    TessProgressDialog 将实现 TessProgressUpdaterInterface

    public class TessProgressDialog extends DialogFragment implements TessProgressUpdaterInterface
    {
        private ProgressBar mProgressBar;
    
        @Override
        public void onUpdate(int p)
        {
            if(mProgressBar != null)
             mProgressBar.setProgress(p);
        }
    }
    

    最后,我有一个接口 TessProgressUpdaterInterface:

    public interface TessProgressUpdaterInterface
    {
        void onUpdate(int p);
    }
    

    现在只要你收到来自异步任务的更新,就调用下面的代码

    if(progressListener != null)
        progressListener.onUpdate(progressValues.getPercent());
    

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多