如何在android中创建一个Browse按钮来加载sdcard中的任何图像

时间:2014-02-27 11:03:55

标签: android

如何在android中创建一个Browse按钮来加载来自SdCard的任何图像? 只允许打开经过验证的扩展文件。

2 个答案:

答案 0 :(得分:1)

如下所示使用它。将下面的代码放在按钮点击事件中。

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);

所以你的完整代码看起来像这样

((Button) findViewById(R.id.Button1))
                .setOnClickListener(new OnClickListener() {

                    public void onClick(View arg0) {

                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent,
                                "Select Picture"), SELECT_PICTURE);
                    }
                });

答案 1 :(得分:1)

  1. 在xml中创建按钮,
  2. 在按钮的onClick监听器中,调用openGallery(),如下所示
  3. Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery();
        }
    });
    
    private void openGallery() {
        Log.v(TAG, "openGallery");
        Intent intent = new Intent();
                //shows all image files in device
        intent.setType("image/jpg"); 
                // or you can use intent.setType("image/*"); to open all image files.
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),
                1);
    }
    
    
    // To handle when an image is selected from the browser, add the following
    // to your Activity
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                // currImageURI is the global variable I'm using to hold the
                // content:// URI of the image
                currImageURI = data.getData();
                            final String imgpath = getRealPathFromURI(currImageURI);
                                //TODO: Got the image file path Do your stuff here
            }
        }
    

    }