问题
Is there any way to change the context of WebView? I mean, when I extend the WebView class I call the super constructor with a context (in my example an activity). Later on, this activity is no longer exists and we move to other activity.
The problem is the WebView is still alive and has a reference to this context. I can't create my WebView any time because the initialisation is long. I tried to call the super class with getApplicationContext() but I found that this also problematic for displaying videos.
What can I do in order to set the WebView's context without create a new one.
Thanks.
回答1:
To pass new context to webview you can create a method to initialize webview, passing an argument of Context like shown below:
public static Webview initializeWebView(Context context)
{
myWebView = new WebView();
return myWebView;
}
And after this you can call this method whereever you want and whenever you want. You can call this as shown below:
myWebView = initializeWebView(YourActivityName.this);
//this way whatever Context you will pass your webview will be initialized that way
//for example you can also pass getApplicationContext() as an Argument
myWebView = initializeWebView(getApplicationContext());
//or
myWebView = initializeWebView(customContext);
this customContext can be any context that is inherited from other context that you wanted to use.
来源:https://stackoverflow.com/questions/26085023/set-a-new-context-to-webview