android - 自定义 SquareView - child 不与 match_parent || 相处包装内容

标签 android android-layout android-view

所以我需要一个始终是正方形的 View ,因此我编写了以下自定义类

public class SquareView extends LinearLayoutCompat
{
    public SquareView(Context context)
    {
        super(context);
    }

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

    public SquareView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width  = getMeasuredWidth();
        int height = getMeasuredHeight();

        if (width > height)
        {
            setMeasuredDimension(width, width);
        }
        else
        {
            setMeasuredDimension(height, height);
        }
    }
}

但是,使用 match_parentwrap_content 的 View 的 subview 不再正常运行

我该如何解决这个问题?

最佳答案

这是对更大问题的回答,而不是修复自定义 View 的方法。

ConstraintLayout 支持调整子项的大小以具有特定的纵横比。如果你想要一个方形的 LinearLayout,你可以将它放在一个 ConstraintLayout 中并强制执行 1:1 的纵横比。

https://developer.android.com/training/constraint-layout/index.html#adjust-the-view-size

Set size as a ratio

You can set the view size to a ratio such as 16:9 if at least one of the view dimensions is set to "match constraints" (0dp). To enable the ratio, click Toggle Aspect Ratio Constraint (callout 1 in figure 10), and then enter the width:height ratio in the input that appears.

If both the width and height are set to match constraints, you can click Toggle Aspect Ratio Constraint to select which dimension is based on a ratio of the other. The view inspector indicates which is set as a ratio by connecting the corresponding edges with a solid line.

For example, if you set both sides to "match constraints", click Toggle Aspect Ratio Constraint twice to set the width be a ratio of the height. Now the entire size is dictated by the height of the view (which can be defined in any way) as shown in figure 11.

关于android - 自定义 SquareView - child 不与 match_parent || 相处包装内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45384573/

相关文章:

java - 从监听器或自定义函数访问 View

在名称中使用时间戳时,Android Studio 无法在构建后启动应用程序

具有多种颜色主题的 Android 小部件

android - EditText setError 图标不起作用

android - 调用 setText() 和 invalidate() 后,TextView 无法在 Canvas 上正确绘制

Android 2D 滚动 ListView ?

android - 如何获取通过 `gradlew install`安装的应用程序的应用程序ID?

Android 在连接到 USB 设备时禁用默认应用程序选择提示

java - 尝试从 URL 读取文本时抛出异常

android - 使 BottomNavigationView 停留在其他 View 下