Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 这是制作ImageView正方形的好方法吗?_Java_Android_Imageview_Android Imageview_Android View - Fatal编程技术网

Java 这是制作ImageView正方形的好方法吗?

Java 这是制作ImageView正方形的好方法吗?,java,android,imageview,android-imageview,android-view,Java,Android,Imageview,Android Imageview,Android View,父布局具有指定的宽度值(50dp),并且高度设置为匹配父布局。在这个布局中,我使用Java添加了一些ImageView小部件,因为父布局已经指定了宽度,我可以将每个ImageView的width和height设置为MATCH\u PARENT,使用Java我可以通过将ImageView的height设置为width使其成为正方形 这是我的代码: public class Icon extends ImageView { public AppIcon(final Context cont

父布局具有指定的宽度值(50dp),并且高度设置为
匹配父布局
。在这个布局中,我使用Java添加了一些
ImageView
小部件,因为父布局已经指定了宽度,我可以将每个
ImageView
widthheight设置为
MATCH\u PARENT
,使用Java我可以通过将
ImageView
height设置为width使其成为正方形

这是我的代码:

public class Icon extends ImageView {

    public AppIcon(final Context context)
    {
        super(context);
    }

    public AppIcon(final Context context, final AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AppIcon(final Context context, final AttributeSet attrs, final int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(final int width, final int height)
    {
        setMeasuredDimension(width, width);
    }

}
这是使每个
图像视图成为正方形的好方法吗?我觉得太简单了,好像少了什么


注意:我的方法是有效的,但我需要确定,一切都很好。

您的代码是有效的,但可以进行增强。请参阅我的代码: 更新了我的代码

图像将根据测量的宽度和高度进行缩放,以较小者为准

public class Icon extends ImageView {

public Icon(final Context context) {
    super(context);
}

public Icon(final Context context, final AttributeSet attrs) {
    super(context, attrs);
}

public Icon(final Context context, final AttributeSet attrs,
        final int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int width, int height) {
    super.onMeasure(width, height);
    int measuredWidth = getMeasuredWidth();
    int measuredHeight = getMeasuredHeight();
    if (measuredWidth > measuredHeight) {
        setMeasuredDimension(measuredHeight, measuredHeight);
    } else {
        setMeasuredDimension(measuredWidth, measuredWidth);

    }

}

}