簡體   English   中英

如何在Android中創建瀏覽按鈕以從SD卡加載任何圖像

[英]How to create a Browse button in android to load any image from sdcard

如何在Android中創建瀏覽按鈕以從SdCard加載任何圖像? 僅允許經過驗證的擴展文件打開。

如下使用。 將以下代碼放入您的按鈕單擊事件中。

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. 在xml中創建按鈕,
  2. 在按鈕的onClick偵聽器中,如下調用openGallery()

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
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM