如何在Fragment类中加载WebView?如何在Android中加载Webview? [英] How to Load WebView in Fragment class? How to load Webview in android?
本文介绍了如何在Fragment类中加载WebView?如何在Android中加载Webview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在应加载的片段中创建WebView.我已经将其添加到我的xml文件中.但是,仅当我扩展Activity类时,findViewById方法才有效.无论如何,我也可以在Fragment中使用它吗?
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);
}
}
推荐答案
请尝试一下,这是 OneFragment 类,Webview需要一个必须使用xml进行夸大的视图
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;
}
和 xml 表示fragment_one
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>
这篇关于如何在Fragment类中加载WebView?如何在Android中加载Webview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文