Reputation: 4230
I'm loading a WebView with application context, in the background, so that when the activity opens, we won't have a time delay of loading the webview.
I have a very simple html file, loaded in the webview, with select component :
<select>
<option value="name1">value1</option>
<option value="name2">value2</option>
<option value="name3">value3</option>
</select>
I initiate the webview in the background, with application context
WebView webView = new WebView(getApplicationContext());
webView.setJavaScriptEnabled(true);
webview.loadUrl("https://www.google.com");
And open it in the activity once its ready :
LinearLayout root = new LinearLayout(this);
root.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
root.setOrientation(LinearLayout.VERTICAL);
root.addView(webView);
setContentView(root);
The webview opens in the activity, BUT, the select components don't open the alert, for picking from the dropdown. The reason for it is - Alert only works with an activity context.
Here's what i tried so far :
WebView webView = new WebView(this);
this works, but it takes time for the webview to load, and its not my intention.I want to stress out, that a solution of sort : don't load the webview in the background is not possible for me, so please, don't suggest it, i'm looking for something that fits my requirements.
Upvotes: 3
Views: 4176
Reputation: 4230
Turns out that a WebView (or any other ui component) doesn't work when setting the context to application context.
Doesn't work :
WebView webView = new WebView(getApplicationContext());
Works :
WebView webView = new WebView(CUURENT_ACTIVITY);
We don't want to use the CURENT_ACTIVITY
when using MutableContextWrapper, which solves the issue (init the WebView with application context, and when the activity opens, we're updating the context with activity context).
InternalContext class :
class InternalContext {
private static InternalContext instance;
private MutableContextWrapper mutableContext;
protected static InternalContext getInstance() {
if (instance == null) {
instance = new InternalContext();
}
return instance;
}
protected void setBaseContext(Context context) {
mutableContext.setBaseContext(context.getApplicationContext());
}
protected MutableContextWrapper getMutableContext() {
return mutableContext;
}
}
When initiating the webview, we're using the mutableContext :
WebView webView = new WebView(InternalContext.getInstance().getMutableContext());
When a new activity starts, we need to update the base context :
InternalContext.getInstance().setBaseContext(CURRENT_ACTIVITY);
Upvotes: 6