How to open phones gallery through code

后端 未结 4 1325
青春惊慌失措
青春惊慌失措 2020-11-29 05:21

I wanna to open phones gallery through a button click.
In my activity I have a button, I want to open the gallery through that button click.

4条回答
  •  醉酒成梦
    2020-11-29 06:02

    Try this example, it worked for me to open my gallery by clicking a Button I am sure this will work for you

    public class MainActivity extends Activity {
    
        private static final int SELECT_PICTURE = 1;
    
        private String selectedImagePath;
        private ImageView img;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            img = (ImageView)findViewById(R.id.imageView1);
    
            ((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);
                        }
                    });
        }
    
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == RESULT_OK) {
                if (requestCode == SELECT_PICTURE) {
                    Uri selectedImageUri = data.getData();
                    selectedImagePath = getPath(selectedImageUri);
                    System.out.println("Image Path : " + selectedImagePath);
                    img.setImageURI(selectedImageUri);
                }
            }
        }
    
        public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
    }
    

    and here is your main.xml should be looks like

    
    
    
    
    
    
    
    

    Also in MainActivity.java, add all these imports

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    

    Apply this example and you are done :)

提交回复
热议问题