所以我需要一个始终是正方形的 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_parent
和 wrap_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/