1
我試圖在我的WebView加載URL之前加載.png圖像,當我啓動我的應用程序時。這裏是我的相同的Java代碼:在WebView上加載URL之前無法加載圖像
package course.org.mywebsite;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
public class MainActivity extends Activity {
WebView mWebView;
ImageView logo;
@Override
public void onCreate(Bundle savedInstanceState)
{
final Activity mActivity = this;
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
super.onCreate(savedInstanceState);
logo = (ImageView) findViewById(R.id.logo);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(MyURLHere);
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
//Make the bar disappear after URL is loaded, and changes string to Loading...
mActivity.setTitle("Loading...");
mActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
logo.setVisibility(View.VISIBLE);
if(progress == 100) {
mActivity.setTitle(R.string.app_name);
logo.setVisibility(View.GONE);
}
}
});
}
}
我的佈局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:visibility="invisible"
android:src="@drawable/logo"/>
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
當我運行的應用程序,它崩潰,出現以下錯誤:
FATAL EXCEPTION: main
Process: course.org.mywebsite, PID: 22730
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
at course.org.sensoredlife.MainActivity$1.onProgressChanged(MainActivity.java:52)
at com.android.webview.chromium.WebViewContentsClientAdapter.onProgressChanged(WebViewContentsClientAdapter.java:239)
at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:169)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
參考此特定代碼行:
logo.setVisibility(View.VISIBLE);
我在這裏錯過了什麼?我已經將圖像分配給「logo」變量,並在URL加載過程中進行設置。
您必須始終設置內容視圖,然後才能通過使用findViewById – TameHog