You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio报错:无法解析setJavaScriptEnabled方法求助

Fixing the "cannot resolve 'setJavaScriptEnabled'" Error in Your Android WebView Code

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.xml layout actually has a WebView with the id webview—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, add android:usesCleartextTraffic="true" to the <application> tag in your AndroidManifest.xml.

内容的提问来源于stack exchange,提问作者Abdelazeez Mabrouk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:18:47