I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?
I already tested the Solution from another Question, but it doesn't work.
public class OneFragment extends Fragment{
public WebView PlanWebView;
public OneFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
// Unknown class: "PlanWebView";
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
Try this please , This is the OneFragment class , Webview needs a view which has to be inflated using xml
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout. fragment_one, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
mWebView.loadUrl("https://google.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
return view;
}
and xml for fragment_one
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>