项目需求:WebView在loadUrl的时候显示一个dialog,加载好之后dismiss这个dialog
aidHomeWebView = (WebView)findViewById(R.id.aidHomeWebView);
aidHomeWebView.loadUrl(URL);
aidHomeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
aidHomeWebView.loadUrl(urlNewString);
return true;
}
@Override
public void onLoadResource(WebView view, String url) {
//SHOW LOADING IF IT ISNT ALREADY VISIBLE
ProgressDialogUtil.showProgressDialog(OceanHouseActivity.this);
}
@Override
public void onPageFinished(WebView view, String url) {
//HIDE LOADING IT HAS FINISHED
ProgressDialogUtil.dismissProgressDialog();
}
});
试了上述方法,发现一个问题,有时dialog出现多次,当dialog消失的时候,页面往往还是没有加载好。
So,换别的方法:
You can do it by setting up a Timer which checks for progress of current page by calling getProgress() and if it is less than some threshold after some specified time then you can dismiss the loading of the current page.
代码如下:
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run() {
setTitle("hear me?");
while(aidHomeWebView.getProgress() != 100){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ProgressDialogUtil.dismissProgressDialog();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.ocean_house);
lay_oceanhouse=(FrameLayout)findViewById(R.id.lay_oceanhouse);
showView();
aidHomeWebView = (WebView)findViewById(R.id.aidHomeWebView);
aidHomeWebView.loadUrl(URL);
ProgressDialogUtil.showProgressDialog(this); // add...
timer.schedule(task, 1000); // add...
returnButton_oceanhouse = (Button)findViewById(R.id.returnButton_oceanhouse);
returnButton_oceanhouse.setOnClickListener(this);
}
成功了!
本文介绍了解决WebView在加载URL时频繁显示dialog并导致页面加载延迟的方法。通过使用定时器检查当前页面加载进度,实现了在页面完全加载后正确关闭dialog,解决了多次显示的问题。

被折叠的 条评论
为什么被折叠?



