Android Studio 3.0开发的扫码APP扫描结果URL无法点击求解决
解决扫码结果URL无法点击的问题
嘿,我帮你搞定这个问题!你的AlertDialog里显示的URL没法点击,是因为默认的setMessage()只是把文本当成普通字符串渲染,不会自动识别链接并设置可点击属性。这里有两种简单的解决办法:
方法一:用SpannableString实现可点击URL
修改你的handleResult方法,把扫描结果包装成可点击的 Spannable 文本,点击URL时直接打开浏览器:
@Override public void handleResult(Result rawResult) { Log.v("TAG", rawResult.getText()); Log.v("TAG", rawResult.getBarcodeFormat().toString()); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); // 把扫描结果转为可点击的 SpannableString SpannableString spannableUrl = new SpannableString(rawResult.getText()); URLSpan urlSpan = new URLSpan(rawResult.getText()) { @Override public void onClick(View widget) { // 点击URL时打开浏览器 Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getURL())); startActivity(intent); // 关闭对话框 ((AlertDialog) widget.getParent().getParent()).dismiss(); } }; spannableUrl.setSpan(urlSpan, 0, spannableUrl.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置对话框的消息为 SpannableString,并让TextView支持点击 TextView messageView = new TextView(this); messageView.setText(spannableUrl); messageView.setMovementMethod(LinkMovementMethod.getInstance()); messageView.setPadding(50, 30, 50, 30); // 增加内边距优化显示 builder.setView(messageView); AlertDialog alert1 = builder.create(); alert1.show(); mScannerView.resumeCameraPreview(this); }
方法二:自定义对话框布局(更简单)
如果觉得第一种方法繁琐,可以直接自定义布局,利用TextView的autoLink属性自动识别URL:
- 在
res/layout下创建dialog_scan_result.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="wrap_content" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/tv_scan_result" android:layout_width="match_parent" android:layout_height="wrap_content" android:autoLink="web" <!-- 自动识别网页链接 --> android:textSize="16sp"/> </LinearLayout>
- 修改
handleResult方法加载自定义布局:
@Override public void handleResult(Result rawResult) { Log.v("TAG", rawResult.getText()); Log.v("TAG", rawResult.getBarcodeFormat().toString()); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); // 加载自定义布局 View dialogView = getLayoutInflater().inflate(R.layout.dialog_scan_result, null); TextView resultTv = dialogView.findViewById(R.id.tv_scan_result); resultTv.setText(rawResult.getText()); builder.setView(dialogView); AlertDialog alert1 = builder.create(); alert1.show(); mScannerView.resumeCameraPreview(this); }
这两种方法都能让扫描出的URL变成可点击状态,点击后会自动打开系统浏览器跳转对应链接,你可以按需选择~
内容的提问来源于stack exchange,提问作者Ricardo F. Seikka
相关产品推荐
相关产品推荐

