WebView使用问题求助:APP运行弹出选择窗口,取消按钮无响应
Hey there, let's work through this WebView issue you're dealing with! That "What to use" popup with browser options is happening because your app isn't set up to handle web content internally—instead, it's asking the system to open links with an external app. And the unresponsive Cancel button ties back to not having proper WebView configuration to handle that scenario. Let's break down the fixes step by step:
1. Attach a WebViewClient to Load Content Internally
The core problem here is missing a WebViewClient for your WebView. Without this, Android defaults to prompting the user to pick an external app for web content. Add this code to your Main_Activity.java:
import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.appcompat.app.AppCompatActivity; public class Main_Activity extends AppCompatActivity { private WebView myWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myWebView = findViewById(R.id.webview); // Enable JavaScript if your target website requires it myWebView.getSettings().setJavaScriptEnabled(true); // Force links to load inside the WebView instead of triggering external prompts myWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; // Confirm we've handled the url loading internally } }); // Load your desired URL here myWebView.loadUrl("https://your-target-website.com"); } }
2. Validate Your activity_main.xml Layout
Ensure your WebView is properly defined in the layout file—no conflicting configurations that might cause odd behavior:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 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" /> </LinearLayout>
3. Add Required Permissions
Don't forget to include the INTERNET permission in your AndroidManifest.xml—without this, your WebView won't be able to load any web content:
<uses-permission android:name="android.permission.INTERNET" />
4. Resolve the Unresponsive Cancel Button
By setting up the WebViewClient as above, you'll eliminate the external app prompt entirely, so the Cancel button issue will disappear on its own. If you still see the prompt after adding the client, double-check that you've attached it before calling loadUrl() in your activity.
Bonus Tips
- For newer Android versions (API 24+), use the updated
shouldOverrideUrlLoading(WebView view, WebResourceRequest request)method for better compatibility. - To handle page loading errors or track progress, extend
WebViewClientfurther and override methods likeonReceivedError()oronPageStarted().
内容的提问来源于stack exchange,提问作者Hleb Butkevich

