Android跨Activity传递图片并动态添加ImageView问题求助
Let's work through this step by step to get your image transfer and dynamic ImageView setup running properly. You're on the right track using Intents, but let's refine the code to fix the rough spots and make it functional.
Step 1: Handle Image Selection & Passing in the First Activity
First, we need to let the user pick an image (from their gallery), then safely pass that image's reference to your workout_loader Activity. Using content URIs is the most reliable way to do this without hitting memory issues.
Here's how to update your loadPullUps() method and add the image selection logic:
// In your first Activity protected void loadPullUps() { // Launch the system image picker Intent pickImageIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(pickImageIntent, 100); // 100 is our custom request code } // Handle the result of the image selection @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // Check if we're handling the right result and it's successful if (requestCode == 100 && resultCode == RESULT_OK && data != null) { // Get the selected image's URI Uri imageUri = data.getData(); // Pass the URI to the workout_loader Activity Intent loadPullUpImage = new Intent(this, workout_loader.class); loadPullUpImage.putExtra("SELECTED_IMAGE_URI", imageUri.toString()); // URI as string to avoid parcel issues startActivity(loadPullUpImage); } }
Note: If you're using AndroidX, consider switching to ActivityResultContracts.GetContent() instead of startActivityForResult—it's the modern, recommended approach—but the code above works for both older and newer Android versions.
Step 2: Receive Image & Add Dynamic ImageView in workout_loader
Now, in your workout_loader Activity, we'll retrieve the image URI, create an ImageView programmatically, and add it to your layout container (like a LinearLayout or FrameLayout).
// In workout_loader.java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_workout_loader_layout); // Replace with your actual layout file // Get the passed image data from the Intent Intent intent = getIntent(); if (intent != null && intent.hasExtra("SELECTED_IMAGE_URI")) { String imageUriString = intent.getStringExtra("SELECTED_IMAGE_URI"); Uri imageUri = Uri.parse(imageUriString); // Get your layout container (make sure this exists in your XML with the ID "image_container") LinearLayout container = findViewById(R.id.image_container); // Create a new ImageView dynamically ImageView dynamicImageView = new ImageView(this); // Set layout parameters to control size and spacing LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ); params.setMargins(16, 16, 16, 16); // Add margins for better spacing dynamicImageView.setLayoutParams(params); // Load the image into the ImageView // For better performance (and to avoid OOM errors), use a library like Glide or Picasso // Example with Glide (add the dependency to your build.gradle first): // Glide.with(this).load(imageUri).into(dynamicImageView); // If you don't want to use a library, use BitmapFactory (note: riskier for large images) try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri); dynamicImageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); dynamicImageView.setImageResource(R.drawable.error_placeholder); // Add a fallback image } // Add the new ImageView to your layout container container.addView(dynamicImageView); } }
Critical Fixes & Pro Tips
Permissions: Don't forget to add image access permissions in your
AndroidManifest.xml:<!-- For Android 12 and below --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <!-- For Android 13+ --> <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />You'll also need to request these permissions at runtime if your target SDK is 23 or higher.
Avoid OOM Errors: Loading large bitmaps directly can crash your app. Libraries like Glide or Picasso handle image resizing and caching automatically—they're way more reliable than raw
BitmapFactoryfor real-world use.Layout Container: Make sure your
workout_loaderlayout has a container (like LinearLayout, ConstraintLayout) with an ID so you can reference it in code to add the dynamic ImageView.
内容的提问来源于stack exchange,提问作者HelpImInTrouble

