0

我有一个AsyncTask可以将进度发布到主要活动。DialogFragment with ProgressBar在任务更新时更新

我也有一个DialogFragment与ProgressBar,我在我的主要活动中创建。

在主要活动中,我首先执行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"); 

我想在主要活动从异步任务收到更新时更新进度栏。有任何想法吗?

回答

1

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

解决方案是重写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());