gpt4 book ai didi

android - 如何在 Fragment 类中加载 WebView?如何在android中加载Webview?

转载 作者:行者123 更新时间:2023-11-30 00:15:47 27 4
gpt4 key购买 nike

我正在尝试在应加载的 fragment 中创建 WebView。我已经将它添加到我的 xml 文件中。但是,findViewById 方法仅在我扩展 Activity 类时才有效。无论如何,我也可以在 Fragment 中使用它吗?

我已经测试了另一个问题的解决方案,但它不起作用。

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 扩展的 View

@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

<?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>

关于android - 如何在 Fragment 类中加载 WebView?如何在android中加载Webview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47322740/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com