我正在尝试使用 Android 教程构建一个应用程序,将 WebView 加载到我构建的移动网站。问题在于跟随教程 startActivity
函数未定义,Android 教程没有帮助。我已完成 Ctrl+Shift+O 以验证是否已加载所有正确的模块。
package com.mysite;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
更新
好的,现在我的代码是这样的:
package com.myapp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MyApp extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//init webview
WebView DCWebView = (WebView) findViewById(R.id.webview);
WebSettings webViewSettings = DCWebView.getSettings();
//when a link is clicked, use the WebView instead of opening a new browser
DCWebView.setWebViewClient(new MyWebViewClient() {
@Override
public void launchExternalBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
});
//enable javascript
webViewSettings.setJavaScriptEnabled(true);
}
}
但我显示了 2 个错误:
Description Resource Path Location Type
The type new MyWebViewClient(){} must implement the inherited abstract method MyWebViewClient.launchExternalBrowser() DealClippings.java /MyApp/src/com/myapp line 21 Java Problem
The method launchExternalBrowser(String) of type new MyWebViewClient(){} must override or implement a supertype method MyApp.java /DealClippings/src/com/myapp line 23 Java Problem
最佳答案
WebViewClient
确实没有startActivity
方法。您可以查看 docs .您必须向 Context
(可能是您的 Activity
)发出信号来执行这些代码行。有许多可能的方法,包括添加监听器或简单地调用抽象方法,您在 Activity 中设置 WebView
的 WebViewClient
时在此类的匿名实例中实现。
例如:
public abstract class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.mysite.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
launchExternalBrowser(url);
return true;
}
public abstract void launchExternalBrowser(String url);
}
然后在您的 Activity 中:
WebViewClient client = new MyWebViewClient() {
@Override
public void launchExternalBrowser(String url) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
};
虽然我不确定您为什么想要这种行为,但它应该或多或少起作用。
关于java - MyWebViewClient 类型未定义方法 startActivity(Intent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8176288/