How to pick an image from gallery (SD Card) for my app?

前端 未结 10 1876
Happy的楠姐
Happy的楠姐 2020-11-21 23:40

This question was originally asked for Android 1.6.

I am working on photos options in my app.

I have a button and an ImageView in my Activity. When I click

10条回答
  •  执念已碎
    2020-11-22 00:08

    public class BrowsePictureActivity extends Activity {
    private static final int SELECT_PICTURE = 1;
    
    private String selectedImagePath;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        ((Button) findViewById(R.id.Button01))
                .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);
                    }
                });
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
            }
        }
    }
    
    public String getPath(Uri uri) {
    
            if( uri == null ) {
                return null;
            }
    
            // this will only work for images selected from gallery
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            if( cursor != null ){
                int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
    
            return uri.getPath();
    }
    
    }
    

提交回复
热议问题