2014-09-25 97 views
1

我的代碼:的WebView和shouldOverrideUrlLoading

public class View_WebView extends Activity { 
    WebView myWebView; 

    private class MyWebViewClient extends WebViewClient { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      if (url.endsWith(".mp4")){ 
      Intent in = new Intent (Intent.ACTION_VIEW , Uri.parse(url)); 
      startActivity(in); 
      return true; 
     } 
     else 
      return false; 
     } 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     myWebView = (WebView) findViewById(R.id.webview); 
     myWebView.setWebViewClient(new WebViewClient());  
     myWebView.loadUrl("http://hdcast.pl"); 
    }  

} 


    <?xml version="1.0" encoding="utf-8"?> 
<WebView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/webview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
/> 

的Eclipse編譯正確,當我啓動我的智能手機我的應用程序,我得到了一個錯誤:

「不幸的是,申請XX已停止」

+0

請你發佈你的logcat? – Shadow 2014-09-25 15:10:50

+0

我智能手機的入口被損壞了... – vifus 2014-09-25 15:52:21

+0

你能不能在這裏顯示logcat .. – Ranjit 2014-09-25 16:24:30

回答

1

您的webView爲空,取消註釋此行:

myWebView = (WebView) findViewById(R.id.webview); 

編輯:

還必須

<WebView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/webview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
/> 
+0

是的...這是必須給這裏的空指針的主要原因.. + 1找到主要問題.. – Ranjit 2014-09-25 15:29:09

+0

錯誤:webview無法解析或不是字段 – vifus 2014-09-25 15:34:36

+0

記得要將webview添加到你的xml中,看看我的編輯 – 2014-09-25 15:37:59

1

你沒有正確使用它在你的XML有一個的WebView元素!

您必須製作自己的自定義WebClient,以擴展WebClient,並在其中根據需要使用shouldOverrideUrlLoading。

http://developer.android.com/guide/webapps/webview.html

private class MyWebViewClient extends WebViewClient { 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     if (url.endsWith(".mp4")){ 
     Intent in = new Intent (Intent.ACTION_VIEW , Uri.parse(url)); 
     startActivity(in); 
     return true; 
    } 
    else 
     return false; 
    } 
} 

然後你自定義的Web客戶端添加到您的WebView,你是好去。

myWebView.setWebViewClient(new MyWebViewClient());  
myWebView.loadUrl("XXX"); 

編輯:根據以前的答案不過,請先確認您初始化您的WebView與findViewById()

1

直接就做:

從這個tutorial

myWebView.setWebViewClient(new WebViewClient() { 
@Override 
public boolean shouldOverrideUrlLoading(WebView view, String url) { 
if (url.endsWith(".mp4")){ 
    Intent in = new Intent (Intent.ACTION_VIEW , Uri.parse(url)); 
    startActivity(in); 
    return true; 
} 
else 
    return false; 
} 
相關問題