如何使用Fragment显示ProgressDialog

时间:2012-04-23 01:09:51

标签: android android-fragments

我有一个Fragment活动,左边有一个ListFragment,右边有一个带有WebView的Fragment。功能正常但我想在网页完成加载时显示一个显示“正在加载...”的进度对话框。我怎样才能完成这个看似微不足道的任务?

以下是我的代码:

public class ArticleListActivity extends FragmentActivity implements
    ArticleListFragment.OnArticleSelectedListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.articlelist_fragment);
    }

    public void onArticleSelected(String contentLink) {
        ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.articleview_fragment);

        if (viewer == null || !viewer.isInLayout()) {
            Intent showContent = new Intent(getApplicationContext(),
                    ArticleViewerActivity.class);

            showContent.setData(Uri.parse(contentLink));
            startActivity(showContent);
        } else {
            viewer.updateUrl(contentLink);
        }
    }
}

这是我的FragmentActivity

public class ArticleViewerActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.articleview_fragment);

        Intent launchingIntent = getIntent();
        String content = launchingIntent.getData().toString();

        ArticleViewerFragment viewer = (ArticleViewerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.articleview_fragment);

        viewer.updateUrl(content);
    }
}

这是我的片段

public class ArticleViewerFragment extends Fragment {

    private ProgressDialog progressBar; 

    private WebView viewer = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        viewer = (WebView) inflater.inflate(R.layout.webview_layout, container, false);
        viewer.loadUrl("file:///android_asset/default.html");
        return viewer;
    }

    public void updateUrl(String newUrl) {
        if (viewer != null) {
            viewer.loadUrl(newUrl);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用此代码:

final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);
pd.setCancelable(false);

webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
    }
});
webview.loadUrl("file:///android_asset/default.html");