首页 > 解决方案 > Resizing Custom ImageView on Orienation Switch

问题描述

I am using the following code:

public class SquareImageView  extends ImageView {
...
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        setMeasuredDimension(width, width);
    }

... }

<com.project.SquareImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:scaleType="centerCrop"/>

To use a square ImageView in my project. It works well, though I want to modify it so that when the user goes into landscape mode the ImageView would have a static height chosen by me. I do not want to create a new layout for it. So, I want to know if it is possible to do what I need on the class level.

I have tried my best to detect the screen orientation change on the class and it failed. Note that I want a smaller version of the ImageView on landscape, I want the image to be cropped to the new height selected by me.

Thanks.

标签: javaandroid

解决方案


Views don't know when the orientation has changed. So you can't do it without some help.

The easiest way to do it is to make a separate xml file for landscape mode, and use whatever ImageView sizes you want. The second easiest way is in you Activity's onCreate to modify the view's layoutParams depending on the orientation.

The other way to do it would be to turn off automatic activity restart on orientation change, then implement an onConfigChange that would call a function on the view onSetOrientation() that tells it what the new orientation is, and then the view can adjust itself accordingly.

But you really don't want to do that. Just go with 2 layouts.


推荐阅读