从图库获取图像并在android studio的另一个活动中预览

时间:2018-12-03 11:43:35

标签: android

我想通过按一个按钮在图库中选择一个图像,然后在另一个活动中预览该图像。

MainActivity

public class MainActivity extends AppCompatActivity {

public  static final  int REQUEST_CODE=1234;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode==REQUEST_CODE && resultCode==Activity.RESULT_OK)
    {

        Intent intent = new Intent(this, Main2Activity.class);
        intent.putExtra("picture",REQUEST_CODE);
        startActivity(intent);

    }
}


public  void send(View view){

    Intent intent=new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,"picture"),REQUEST_CODE);

}

从此代码按钮访问Gallery并将其传递给Main2Activity。

Main2Activity

public class Main2Activity extends AppCompatActivity {

ImageView iv;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    Intent intent = getIntent();
    Bitmap bitmap = (Bitmap) intent.getParcelableExtra("picture");
    iv = (ImageView)findViewById(R.id.imageView);
    iv.setImageBitmap(bitmap);

}
}

在此代码中我们可以打开图库并选择图片。选择图片后,它会打开第二个活动,但不会预览图片。

1 个答案:

答案 0 :(得分:1)

MainActivity

@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(requestCode==REQUEST_CODE && resultCode==Activity.RESULT_OK)
            {
                Uri selectedImageUri = data.getData( );

                Intent i= new Intent(MainActivity.this,Main2Activity.class);
                i.setData(selectedImageUri);
                startActivity(i);
            }
        }

Main2Activity

public class Main2Activity extends AppCompatActivity {

        private ImageView imageView;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);

            imageView = findViewById(R.id.img);

            if(getIntent()!= null){
            Uri imageUri=getIntent().getData();
            imageView.setImageURI(imageUri);

            }
        }
    }