set a new context to WebView

这一生的挚爱 提交于 2019-12-08 05:17:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!