首页 > 解决方案 > 片段中的 webview 场景问题

问题描述

安卓新手,如有错误请见谅

FiveFragment.java 的问题,其中mWebview变量用红色下划线,“无法解析符号 mWebview”

frament_five.xml:

<?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"
tools:context="com.example.ekatechhp.pkmapplication.FiveFragment">
<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
   </RelativeLayout>

片段五.java:

@SuppressLint("ValidFragment")
public class FiveFragment extends Fragment {
public FiveFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view=inflater.inflate(R.layout. fragment_five, 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;
}
}

标签: android

解决方案


在你的程序中声明 WebView就像这个 WebView mWebview;

@SuppressLint("ValidFragment")
public class FiveFragment extends Fragment {

WebView mWebview ;//declare here

public FiveFragment() {
    // Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
savedInstanceState) {
View view=inflater.inflate(R.layout. fragment_five, 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;
  }
 }

并确保你导入这个

import android.webkit.WebView; 

推荐阅读