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

onSingleClick中添加if后失效?双击需实现内嵌PDF加载功能求助

解决你的HorizontalScrollView图片点击问题

嘿,我看到你遇到了两个问题:单击图片的Toast没反应,还有双击要加载内嵌PDF的需求,这就帮你搞定!

一、修复单击Toast失效的问题

你当前的单击逻辑失效,核心原因是你把TextView对象和字符串直接比较了,而不是拿TextView的文本内容来判断。

看你原来的代码:

if(textView.equals("ENG")) { ... }
if (textView.equals("")) { ... }

这里textView是一个TextView实例,和字符串"ENG"永远不会相等,所以这两个判断根本不会触发。你得改成获取TextView的文本内容后再比较,而且用字符串常量调用equals更安全,能避免空指针问题:

修正后的onSingleClick方法:

@Override
public void onSingleClick(View v) {
    // 获取文本并去除可能的空格
    String currentLang = textView.getText().toString().trim();
    if ("ENG".equals(currentLang)) {
        Toast.makeText(getApplicationContext(), "eng single", Toast.LENGTH_SHORT).show();
    } else if (currentLang.isEmpty()) {
        Toast.makeText(getApplicationContext(), "nl single", Toast.LENGTH_SHORT).show();
    }
}

这样单击图片就能根据TextView的内容显示对应的Toast了。

二、实现双击加载内嵌PDF的功能

要加载应用里内嵌的PDF,得先把PDF放到assets文件夹(没有的话在项目根目录新建一个),然后通过下面的步骤来实现:

1. 把assets里的PDF复制到内部存储

系统的PDF查看器没法直接访问assets目录的文件,所以得先把PDF复制到应用的内部存储里:

private File copyPdfToLocal(String pdfName) {
    File localPdf = new File(getFilesDir(), pdfName);
    // 如果文件已经存在,直接返回,不用重复复制
    if (localPdf.exists()) {
        return localPdf;
    }

    try (InputStream in = getAssets().open(pdfName);
         OutputStream out = new FileOutputStream(localPdf)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Failed to prepare PDF", Toast.LENGTH_SHORT).show();
        return null;
    }
    return localPdf;
}

2. 在双击事件里打开PDF

修改onDoubleClick方法,调用上面的复制方法,然后启动系统PDF查看器:

@Override
public void onDoubleClick(View v) {
    // 替换成你assets里的PDF文件名,比如"fruit_guide.pdf"
    File pdfFile = copyPdfToLocal("your_pdf_file.pdf");
    if (pdfFile == null) {
        return;
    }

    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
    // Android 7.0+必须用FileProvider来获取URI
    Uri pdfUri = FileProvider.getUriForFile(activity_fruit.this,
            getPackageName() + ".fileprovider", pdfFile);
    pdfIntent.setDataAndType(pdfUri, "application/pdf");
    // 给PDF查看器授予读取权限
    pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(pdfIntent);
    } catch (ActivityNotFoundException e) {
        // 如果用户没装PDF查看器,提示一下
        Toast.makeText(getApplicationContext(), "No PDF viewer found on your device", Toast.LENGTH_SHORT).show();
    }
}

3. 配置FileProvider(必须步骤)

Android 7.0及以上禁止直接传递file://格式的URI,所以得配置FileProvider:

  • 首先在AndroidManifest.xml里添加Provider声明:
<application ...>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>
  • 然后在res/xml目录下新建file_paths.xml文件(没有xml目录就新建一个):
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 允许访问应用内部存储的根目录 -->
    <files-path name="pdf_files" path="." />
</paths>

完整的修正后代码

public class activity_fruit extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Fruit");
        setContentView(R.layout.activity_fruit);
        textView = findViewById(R.id.txtstatus);
        textView.setText(((Globals) this.getApplication()).getTaal());

        int fruit1 = R.drawable.kumato;
        ImageView targetImageView1 = findViewById(R.id.img_fruit1);
        targetImageView1.setOnClickListener(new DoubleClickListener() {
            @Override
            public void onSingleClick(View v) {
                String currentLang = textView.getText().toString().trim();
                if ("ENG".equals(currentLang)) {
                    Toast.makeText(getApplicationContext(), "eng single", Toast.LENGTH_SHORT).show();
                } else if (currentLang.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "nl single", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onDoubleClick(View v) {
                File pdfFile = copyPdfToLocal("your_pdf_file.pdf");
                if (pdfFile == null) {
                    return;
                }

                Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                Uri pdfUri = FileProvider.getUriForFile(activity_fruit.this,
                        getPackageName() + ".fileprovider", pdfFile);
                pdfIntent.setDataAndType(pdfUri, "application/pdf");
                pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                try {
                    startActivity(pdfIntent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(getApplicationContext(), "No PDF viewer found on your device", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Glide.with(this)
                .load(fruit1)
                .into(targetImageView1);
    }

    private File copyPdfToLocal(String pdfName) {
        File localPdf = new File(getFilesDir(), pdfName);
        if (localPdf.exists()) {
            return localPdf;
        }

        try (InputStream in = getAssets().open(pdfName);
             OutputStream out = new FileOutputStream(localPdf)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Failed to prepare PDF", Toast.LENGTH_SHORT).show();
            return null;
        }
        return localPdf;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:37:04