I'm having a lot of trouble getting this to work correctly. I have an ImageView
and a TextView
, both in a LinearLayout
. I want the ImageView
to take up as much of the parent view as possible without cropping or changing the aspect ratio, but leaving enough room for the TextView directly below it. I have this mostly working, but when the height of the image is small enough to leave extra space in the parent view, the TextView only appears at the very bottom of the LinearLayout
, as opposed to just below the image.
I've tried many combinations of layout parameters, fiddling with the gravity, weight, height, and width of both the ImageView and the TextView. I even tried using a RelativeLayout
, but the results were very inconsistent.
Here is the relevant portion of my code:
// Create a vertical linear layout to hold the image with the caption below
// it, taking up as much space on the screen as possible
LinearLayout ll = new LinearLayout(context);
ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
ll.setOrientation(LinearLayout.VERTICAL);
ll.setGravity(Gravity.CENTER);
// Get the image view
ImageView img = new ImageView(context);
LayoutParams ilp = new LayoutParams(LayoutParams.MATCH_PARENT, 0);
ilp.weight = 1;
ilp.gravity = Gravity.CENTER;
img.setLayoutParams(ilp);
// Create the caption view
TextView cap = new TextView(context);
cap.setText("Example caption text");
LayoutParams clp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
clp.weight = 0;
clp.gravity = Gravity.CENTER_HORIZONTAL;
cap.setLayoutParams(clp);
// Add views to the linear layout
ll.addView(img);
ll.addView(cap);
// Load the image using an AsyncTask
loadImageTask = new LoadCachedImageTask(context, img, pos);
loadImageTask.execute("image src");
Here's an image of the "good behaviour," where the image is scaled up to the point where the text is still visible:
Here's an image of the "bad behaviour," where there is room above and below the image, but the text still stays at the bottom: