我正在开发一个关于大学应用程序的实习项目,在运行应用程序的这一部分时突然接近。这是我可以将照片上传到图库的部分。我没有收到任何错误,但这里 startActivityForResult(pickImage,REQ);它说像“startActivityForResult(android.content.Intent, int)”作为警告被弃用。
private String category;
private final int REQ= 1;
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_image);
selectImage = findViewById(R.id.addGalleryImage);
imageCategory = findViewById(R.id.image_category);
uploadImage = findViewById(R.id.uploadImageBtn);
galleryImageView = findViewById(R.id.galleryImageView);
String[] items = new String[]{"Select Category", "Convovation", "INdependence Day","Other Events"};
imageCategory.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items));
imageCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
category = imageCategory.getSelectedItem().toString();
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
private void openGallery(){
Intent pickImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickImage,REQ);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
galleryImageView.setImageBitmap(bitmap);
}
}
}
答案 0 :(得分:1)
如果您想从设备中选取图像,请使用较新的 startActiityForResult() 替代方法,它是 - ActivityResultLauncher
只需按照以下步骤操作:-
首先像这样创建 ActivityResultLauncher :
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new
GetContent(),
new ActivityResultCallback<Uri>() {
@Override
public void onActivityResult(Uri uri) {
// Handle the returned Uri
}
});
然后,单击按钮或根据需要启动系统图像选择器。
@Override
public void onCreate(@Nullable savedInstanceState: Bundle) {
Button selectButton = findViewById(R.id.select_button);
selectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Pass in the mime type you'd like to allow the user to select
// as the input
mGetContent.launch("image/*");
}
});
}
如您所见,您没有在任何地方看到 REQUEST_CODE。因此,使用 ActivityResultLauncher,您不必担心检查不同任务的不同请求代码。如果一切正常,ActivityResultLauncher 会为您提供最终结果。
您可以在此处找到更多相关信息:- https://developer.android.com/training/basics/intents/result