如何創建ProgressDialog而不顯示它?當WebView開始嘗試打開頁面時,如果頁面在兩秒後未加載(如果它在30秒後仍未加載,則消失),我想要顯示一個進度對話框。以下代碼失敗,因爲ProgressDialog progress = new ProgressDialog(MainActivity.this);
,儘管我在各種SO答案中看到了,但會引發NullPointerException錯誤。Android - 創建ProgressDialog而不顯示它
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
// ProgressDialog progress = new ProgressDialog(MainActivity.this); // gives NullPointerException
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
webView.setWebViewClient(new WebViewClient() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap facIcon) {
timerBeginDialog(2000, progress);
progress.setCancelable(true);
timerRemoveDialog(30000, progress);
}
@Override
public void onPageFinished(WebView view, String url) {
drawer.closeDrawer(GravityCompat.START);
progress.dismiss();
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/www/error.html");
drawer.openDrawer(GravityCompat.START);
progress.dismiss();
}
});
.
.
}
public void timerBeginDialog(long time, final ProgressDialog pd){
new Handler().postDelayed(new Runnable() {
public void run() {
pd = ProgressDialog.show(MainActivity.this, "", "Loading...", true); // gives error "Cannot assign a value to final variable pd"
}
}, time);
}
public void timerRemoveDialog(long time, final ProgressDialog pd){
new Handler().postDelayed(new Runnable() {
public void run() {
pd.dismiss();
}
}, time);
}
我把它裏面'onCreate',也有聲明它爲final:'最終ProgressDialog progress = new ProgressDialog(MainActivity.this);',並且還更改不必要的第二個聲明'pd = ProgressDialog.show(MainActivity.this,「」,「Loading ...」,true) ;'timerBeginDialog'內部到'pd.show();'。 – Bazley