I am working on an app with a navigation drawer that can show several screens. These pages are all shown within the same Activity
though by inflating them into a wrapper.
<android.support.design.widget.CoordinatorLayout
//some parameters
<include
android:id="@+id/main_container"
layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
One of these screens contains a WebView
.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/webview_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/app_bar_main">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
To the Webview I attach a WebViewClient
to handle some html manipulation with Javascript.
WebView webView = findViewById(R.id.web_view);
if (webView == null) {
inflateLayout(R.layout.layout_with_webview);
webView = findViewById(R.id.web_view);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new CustomWebViewClient());
webView.loadUrl("http://www.somesite.com");
If I put the WebView
into the layout that is loaded with setContentView()
when the activity starts everything loads correctly. After that I inflate a different Layout into the main_container
using the following code:
public void inflateLayout(int toinflate) {
ConstraintLayout mainLayout = findViewById(R.id.main_container);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(toinflate, null);
mainLayout.removeAllViews();
mainLayout.addView(layout);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
When I now want to inflate a Layout containing a WebView
nothing is shown when I call webView.loadUrl("some url")
eventhough the onPageFinished(...)
method is being called.
Now the question is: what am I doing wrong and how can I use WebViews that are attached to the Screen using inflation.
Also: I already tried adding the WebView using addView
and it did not work.