java - 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.
解决方案
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.
推荐阅读
- xamarin - Android 应用程序不断停止 - 启动错误
- json - com.mongodb.util.JSONParseException:
- kubernetes - 如何将动态 IP 设置为属性文件?
- c++ - 我将 QPixmap 传递给 QAbstractButton::setIcon 而不是 QIcon,但我没有收到错误...为什么?
- excel - 运行时错误“1004”无法访问该文件。尝试以下方法之一:
- java - 当我在java中有“”时如何返回null?
- serialization - Django rest 框架 - 模型序列化程序不会序列化所有字段
- java - Java - 写入文件时按字面意思使用转义的反斜杠
- javascript - 未捕获的类型错误:无法读取未定义的属性“tb”
- javascript - Websocket 自定义服务器不能与 Firefox 一起使用,但可以与 Chrome 一起使用