如何在WebView Activity中打开URL?代码改造技术求助
如何将扫码后的链接从系统浏览器改为WebView内打开
没问题,我来帮你搞定这个需求,咱们分几步来修改:
1. 新建带WebView的Activity
首先你需要创建一个专门用来加载链接的WebViewActivity,先写布局文件res/layout/activity_web_view.xml:
<?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/web_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
然后写WebViewActivity的Java代码,关键是设置WebViewClient来阻止链接跳转到系统浏览器,同时配置必要的WebView参数:
public class WebViewActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); webView = findViewById(R.id.web_view); // 启用JavaScript(如果目标网页需要的话) WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); // 设置WebViewClient,让链接在当前WebView内打开 webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(request.getUrl().toString()); return true; } }); // 获取从BarcodeScannerActivity传递过来的链接并加载 String url = getIntent().getStringExtra("SCAN_URL"); if (url != null && !url.isEmpty()) { webView.loadUrl(url); } } // 处理返回键,让WebView能回退到上一页 @Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } }
2. 修改BarcodeScannerActivity的跳转逻辑
找到你原来扫描完成后打开浏览器的代码(应该是类似Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(scanContent)); startActivity(intent);这样的),把它替换成跳转到WebViewActivity的代码:
// 替换原来的浏览器跳转代码 Intent webViewIntent = new Intent(BarcodeScannerActivity.this, WebViewActivity.class); webViewIntent.putExtra("SCAN_URL", scanContent); // 把扫码得到的链接传过去 startActivity(webViewIntent);
3. 配置AndroidManifest.xml
- 首先添加网络权限(因为WebView需要加载网页):
<uses-permission android:name="android.permission.INTERNET" />
- 然后注册
WebViewActivity:
<activity android:name=".WebViewActivity" />
这样修改后,扫码得到链接就会直接在你自己的WebView里打开,而不是调用系统浏览器啦。
内容的提问来源于stack exchange,提问作者user1833487
相关产品推荐
相关产品推荐

