要从图库中获取多张图片并在选择后显示在LinearLayout中,你可以按照以下步骤进行:
以下是一个简单的示例代码,展示了如何实现上述功能:
// 请求权限
private static final int REQUEST_CODE_GALLERY = 100;
private static final int REQUEST_CODE_PERMISSION = 200;
private void requestPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
} else {
openGallery();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
// 打开图库
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Images"), REQUEST_CODE_GALLERY);
}
// 处理选择结果
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_GALLERY && resultCode == RESULT_OK && data != null) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
for (int i = 0; i < count; i++) {
Uri imageUri = data.getClipData().getItemAt(i).getUri();
addImageToLayout(imageUri);
}
} else if (data.getData() != null) {
Uri imageUri = data.getData();
addImageToLayout(imageUri);
}
}
}
// 显示图片
private void addImageToLayout(Uri imageUri) {
ImageView imageView = new ImageView(this);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
LinearLayout linearLayout = findViewById(R.id.linearLayout);
linearLayout.addView(imageView);
}
通过上述步骤和代码示例,你可以实现从图库中获取多张图片并在LinearLayout中显示的功能。
领取专属 10元无门槛券
手把手带您无忧上云