Android Studio报错:无法解析setJavaScriptEnabled方法求助
Hey there, let's break down what's going wrong here and fix it up—your code has a couple of key structural issues that are causing this error (and would lead to crashes even if the compiler error went away):
First: You're running code in the wrong place
Right now, you’ve put your WebView setup code directly in the class’s top-level scope, not inside a method like onCreate(). In Java, you can’t just run method calls (like webSettings.setJavaScriptEnabled(true);) directly in the class body—you can only define variables, methods, or inner classes there. This is why the compiler is getting confused and can’t resolve that method call properly.
Second: You're initializing the WebView too early
You’re trying to find the WebView with findViewById() before you’ve loaded your layout with setContentView(R.layout.activity_main);. At that point, the layout hasn’t been inflated yet, so findViewById() will return null—and trying to call getSettings() on a null WebView would crash your app as soon as it launches.
Here's your fixed code
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Load the layout FIRST // Now set up the WebView WebView mywebview = findViewById(R.id.webview); WebSettings webSettings = mywebview.getSettings(); webSettings.setJavaScriptEnabled(true); mywebview.loadUrl("http://www.example.com"); } }
A few extra checks to make sure everything works:
- Double-check that your
activity_main.xmllayout actually has a WebView with the idwebview—if it doesn’t,findViewById()will still return null. Here’s a quick example of what that should look like:<WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> - If you’re using AndroidX instead of the old support library, swap out the import line for
import androidx.appcompat.app.AppCompatActivity; - Starting with Android 9.0 (API level 28), plain HTTP URLs are blocked by default. If you need to load
http://www.example.com, addandroid:usesCleartextTraffic="true"to the<application>tag in yourAndroidManifest.xml.
内容的提问来源于stack exchange,提问作者Abdelazeez Mabrouk

