开发者

Android App development - WebView is not working

Android allows content of a URL to be displayed within an application using WebView. However, for some reason it's not working for me. Below is the code that Iam using:

package com.news;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class NewsActivity extends Activity {
    WebView mWebView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setWebViewClient(new NewsClient());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.loadUrl("http://www.androidpeople.com");
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();            
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class NewsClient extends WebViewClient {

      开发者_开发技巧  public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("URL: " + url);
            view.loadUrl(url);
            return true;
        }
    }
}


It is obvious!

You are implementing a new WebViewClient in which you are overriding shouldOverrideUrlLoading method. This method is called for each url you are loading. And what are you doing there? You are returning true (which means loading should be overriden) and then beginning to load the same url! Thus, the url loading will never occur.

Just delete that line:

mWebView.setWebViewClient(new NewsClient());


add this in your android manifest if not added:

<uses-permission android:name="android.permission.INTERNET" />

this line must be inside the <manifest> element of your AndroidManifest.xml file.


Add this line: mWebView.setWebViewClient(new NewsClient());

But shouldOverrideUrlLoading should return false.


Your code is working in my android device 4.2.2, there is no problem in your implementation, the only thing that you need to do is Override your method like this:

   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
        System.out.println("URL: " + url);
        view.loadUrl(url);
        return true;
    }

This method


You are implementing a new WebViewClient in which you are overriding shouldOverrideUrlLoading method. If you need more info visit here: https://weblearners.blogspot.com/2021/06/how-to-enable-video-image-and-file-upload-in-android-webview-app.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜