如何在android中的button.onClick()中的片段内使用startActivity()

时间:2015-07-27 15:52:15

标签: android pdf android-intent fragment start-activity

我有这个片段http://prntscr.com/7xlkyy 当我点击按钮OPEN时,我想开始新的活动,这将打开pdf文件。

@Override
public void onBindViewHolder(final PersonViewHolder personViewHolder, int i) {
    final int j = i;
    personViewHolder.pdfName.setText(pdfItems.get(j).name);
    personViewHolder.pdfSize.setText(pdfItems.get(j).size);
    personViewHolder.pdfPhoto.setImageResource(pdfItems.get(j).photoID);

    personViewHolder.open.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File file = new File("/" + pdfItems.get(j).getName());
            PackageManager packageManager = v.getContext().getPackageManager();
            Intent testIntent = new Intent(Intent.ACTION_VIEW);
            testIntent.setType("application/pdf");
            List list = packageManager.queryIntentActivities(testIntent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            if (list.size() > 0 && file.isFile()) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                Uri uri = Uri.fromFile(file);
                intent.setDataAndType(uri, "application/pdf");
                // **startActivity(intent);**
            }
        }
    });
}

问题在于它说'#34;无法解析方法startActivity()",它也说'#34;无法解析方法getActivity()"

任何帮助..

3 个答案:

答案 0 :(得分:2)

使用:

((Activity)v.getContext()).startActivity(intent);

答案 1 :(得分:1)

您可以从onClick方法的View参数中获取上下文,如下所示:

v.getContext().startActivity(i);

在你的情况下:

personViewHolder.open.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        File file = new File("/" + pdfItems.get(j).getName());
        PackageManager packageManager = v.getContext().getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent,
                PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0 && file.isFile()) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, "application/pdf");
            v.getContext().startActivity(intent);
        }
    }
}); 

答案 2 :(得分:0)

getActivity().startActivity(new Intent(getActivity(), YourActivity.class));