单击按钮从电话中选择pdf文件,并在textview中显示其文件名 [英] Select pdf file from phone on button click and display its file name on textview

查看:106
本文介绍了单击按钮从电话中选择pdf文件,并在textview中显示其文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在单击按钮时从电话中选择pdf文件,并在文本视图中显示其文件名.到现在为止,我已经完成了打开文件管理器的操作,以单击按钮选择pdf

I want to select pdf file from phone on button click and display its file name on a text view. till now I have done opening file manager for selecting pdf on button click

btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("application/pdf");
            startActivity(intent);
        }
    });

如何在textview上获取选定的文件名?

how do I get the selected file name on textview??

推荐答案

startActivity(intent); 位置使用 startActivityForResult(intent,1212)并执行在 onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case 1212:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file
            Uri uri = data.getData();
            String uriString = uri.toString();
            File myFile = new File(uriString);
            String path = myFile.getAbsolutePath();
            String displayName = null;

            if (uriString.startsWith("content://")) {                   
                Cursor cursor = null;
                try {                           
                    cursor = getActivity().getContentResolver().query(uri, null, null, null, null);                         
                    if (cursor != null && cursor.moveToFirst()) {                               
                        displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                    }
                } finally {
                    cursor.close();
                }
            } else if (uriString.startsWith("file://")) {           
                displayName = myFile.getName();
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

这篇关于单击按钮从电话中选择pdf文件,并在textview中显示其文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆