如何为webview创建包装器对象

时间:2016-01-27 19:32:01

标签: java android webview

所以我有一个简单的工作webview,但大部分工作都是在主要活动中完成的。我试图将它分解为它自己的小类,所以我可以在运行中将其他类加载到主要活动中。我被困在如何做到这一点。我已经尝试了几次并且一直在调试它但我不知道我是否使用了正确的findByValue(R.id.webView);这件事。它一直给我一个

  

引起:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'android.view.View android.webkit.WebView.findViewById(int)'

问题。我已经尝试将引用作为参数传递,并且还对其进行了硬编码。我错过了什么,但不知道是什么。我的activity_main中有一个名为wevView的WebView,这是我试图找出我错误的地方。

感谢您提供任何帮助。

所以这是我的webview类:

public class NewWebView {

//variables need for webview
private final String myPage = "http://www.google.com";
WebView myWebView = null;


//consturctor
public NewWebView(){}
//This method creates the WebView
public void createWebView(WebView webView)
{
    //WebView code
    //Find the Webview in the Activity.xml file
   //myWebView = webView;
    myWebView = (WebView)myWebView.findViewById(R.id.webview);
   // myWebView = (android.webkit.WebView)findViewById(R.id.webview);

    //Use the custom WebViewClient for internal app browsing
    myWebView.setWebViewClient(new MyWebViewClient());
    //now for enabling the settings
    WebSettings webSettings = myWebView.getSettings();
    //Enable JavaScript
    webSettings.setJavaScriptEnabled(true);
    //Enable andriod zoom features
    webSettings.setBuiltInZoomControls(true);
    //Loading the Url
    myWebView.loadUrl(myPage);

}


//Methods Used for WebViewer
//custom WebViewClent needed for internal app navigatiion

private class MyWebViewClient extends WebViewClient
{
    public boolean shouldOverRideUrlLoading(android.webkit.WebView view, String url)
    {
        if(Uri.parse(url).getHost().equals(myPage))
        {
            //this is Apivita remain in the APP
            return false;
        }
        /*
        //if it is not in my site redirect it to mobile browers
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
        */
        return true;
    }
}

//Enable the use of the system back button for navigation
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    //if the back button was pushed
    if((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack())
    {
        myWebView.goBack();
        return true;
    }
    //if not

    return  false;

}
}

这是主要的活动

public class MainActivity extends AppCompatActivity {
WebView myWebView = null;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //create the webview
    myWebView = (android.webkit.WebView)findViewById(R.id.webview);
    NewWebView apWebView = new NewWebView();
    apWebView.createWebView(myWebView);

}
}

1 个答案:

答案 0 :(得分:1)

看起来您正在主要活动中找到您的webview,然后将其传递到您的班级。在您的自定义课程中,您将尝试查找另一个技术上已有的视图。因此它试图在webview中找到webview。它显然无法找到它,所以它是空的。

理论上,您应该只能使用myWebView = webView;,但是,您需要确保它首先找到它。

相关问题