10
votes

I want to have an ImageView with width=fill_parent, and the height should be whatever the width is. I'm not sure if there's a way to specify that in xml, is the only option to create my own ImageView-derived class?:

public class MyImageView extends ImageView {

    // Just return whatever the current width is?
    private int measureHeight(int measureSpec) {
        return getWidth();
    }
}

Is this the way to go, any other options? (I'm not sure if the above is even correct, not sure if the width measurement even takes place before the height measurement for example)

Thanks

2
If you set your width to fill_parent, the method getWidth() will return 0. this approach will not work.digulino

2 Answers

11
votes

You can get the width with the method

imageView.getMeasuredWidth();

So, you can set it's height

imageView.setLayoutParams(new LayoutParams(imageView.getMeasuredWidth(), imageView.getMeasuredWidth()));
0
votes

Make layout height equal to the width:

The problem with digulino's answer (in my case at least) is that if you want to change the dimensions in the start, getMeasuredWidth() will return 0 because the views haven't been drawn yet.

You can still do it by using a Runnable() thread like this:

FrameLayout frame = (FrameLayout)findViewById(R.id.myFrame);
frame.post(new Runnable() {
    @Override
    public void run() {
        RelativeLayout.LayoutParams lparams;
        lparams = (RelativeLayout.LayoutParams) frame.getLayoutParams();
        lparams.height = frame.getWidth();
        frame.setLayoutParams(lparams);
        frame.postInvalidate();
    }
});

Important Note: This example assumes your view is a FrameLayout inside a RelativeLayout. Change it accordingly for other layouts.