gpt4 book ai didi

android - 从图库中选择图像或从相机拍摄

转载 作者:太空狗 更新时间:2023-10-29 16:13:38 25 4
gpt4 key购买 nike

我必须制作一个按钮,提供从图库中选择图像或从相机拍摄的图像。

 private void showFileChooser() {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageView.setImageURI(selectedImage);
}

break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
imageView.setImageURI(selectedImage);
}
break;
}
}

结果是有效的。如果我从图库中选择,图像查看器将查看它,如果我选择从相机拍照,它也可以工作。问题是,在我的 showFileChooser() 方法中,我的所有 Intent 都同时运行,所以当我从图库中选择时,相机也在运行。我选择相机,画廊也正在开放。我想我应该在 switch case 模式下实现我的代码,但我不知道该怎么做。请帮助解决我的初学者问题。

最佳答案

添加一个 alertDialog,然后在 onActivityResult 中使用 REQUEST_CAMERASELECT_FILE 而不是 0 和 1 的情况.您将在代码中声明:

private static final int REQUEST_CAMERA = 1;
private static final int SELECT_FILE = 2;

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mActivity);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {

if (items[item].equals("Take Photo")) {
PROFILE_PIC_COUNT = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
PROFILE_PIC_COUNT = 1;
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,SELECT_FILE);
} else if (items[item].equals("Cancel")) {
PROFILE_PIC_COUNT = 0;
dialog.dismiss();
}
}
});
builder.show();

关于android - 从图库中选择图像或从相机拍摄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36306079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com