給一個(gè)項(xiàng)目中的webview頁面提示框優(yōu)化處理:
- 之前顯示的是這樣:
</div>
<img src="http://upload-images.jianshu.io/upload_images/3154077-fb19cf86b9cc64a3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="網(wǎng)頁效果" align=center />
</div> - 現(xiàn)在的效果:
</div>
<img src="http://upload-images.jianshu.io/upload_images/3154077-6a792d7ff141b9f5.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" width = "200" height = "200" alt="原生效果" align=center />
</div>
可以看到標(biāo)題的樣式發(fā)生了改變,其實(shí)我們可以改變對(duì)話框里所有的內(nèi)容.
處理方法:
private class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsConfirm(WebView view, String url, final String message, final JsResult result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("溫馨提示:")
.setMessage(message)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();//這里必須調(diào)用,否則頁面會(huì)阻塞造成假死
// mWebView.reload();//重新刷新頁面
}
})
.setNegativeButton("取消",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
result.cancel();
}
})
.show();
}
});
return true;
}
}
關(guān)鍵點(diǎn)
- 自定義ChromClient,設(shè)置在webview中
- 之前看文章說是在onJsAlert方法中,加入自己寫的AlertDialog,但是沒效果,斷點(diǎn)也進(jìn)不去,后來我在onJsConfirm方法中加載了這個(gè)AlertDialog,發(fā)現(xiàn)效果實(shí)現(xiàn)了.
- 重中之重:記得在取消和確認(rèn)的時(shí)候處理result,并且如果AlertDialog是點(diǎn)擊外部取消的話,也要處理result在cancel掉的結(jié)果,否則會(huì)造成webview頁面塞假死
- 可能會(huì)需要AppCompat的主題,之前我用5.1的Theme.noActionBar之類的主題,崩潰了,現(xiàn)在是Theme.AppCompat.Light
抓取網(wǎng)頁代碼
<a onclick="return confirmRemoveWishlistItem();" title="刪除項(xiàng)目" class="btn-remove btn-remove2">取消收藏</a>
function confirmRemoveWishlistItem() {
return confirm('您是否確認(rèn)要從我的收藏中刪除該產(chǎn)品?');
}
可以看到j(luò)s代碼是調(diào)用了confirm方法的,所以我們?cè)趏nJsAlert方法設(shè)置無效,所以大家可以多試試,有時(shí)候也許前端寫的代碼是alert的,那我們?cè)趏nJsConfirm中設(shè)置肯定是無效的.