Tre*_*vor 4 android relativelayout
我有一个扩展的RelativeLayout,当使用编程定位和大小时RelativeLayout.LayoutParams,需要将自己限制在给定的宽高比.通常,我希望它将自己约束为1:1,因此如果RelativeLayout.LayoutParams包含width200和height100的100,则自定义RelativeLayout将自身约束为100 x 100.
为了达到类似的目的,我已经习惯于覆盖onMeasure()普通的自定义View.例如,我创建了自己的SVG图像转换器,并且View渲染SVG图像的自定义具有重写onMeasure(),以确保调用setMeasuredDimension()包含(a)符合原始测量规范的尺寸,以及(b)匹配宽高比原始SVG图像.
回到我的习惯RelativeLayout,我希望以类似的方式约束自己,我试过压倒onMeasure()但我没有取得多大成功.知道RelativeLayout我的onMeasure()所有子项View放置,我目前通常尝试做的,但没有预期的结果,是覆盖onMeasure(),以便我最初修改维度规范(即应用我想要的约束)然后打电话super.onMeasure().像这样:
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// Restrict the aspect ratio to 1:1, fitting within original specified dimensions
int chosenDimension = Math.min(chosenWidth, chosenHeight);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
Run Code Online (Sandbox Code Playgroud)
什么其实我这样做的时候发生的事情是,奇怪的是,高度正确限制,因为我打算,但宽度是没有的.为了显示:
RelativeLayout.LayoutParams在我的自定义结果中指定高度200和宽度100,RelativeLayout高度为100,宽度为100. - >正确.
RelativeLayout.LayoutParams在我的自定义结果中指定高度为100和宽度为200,RelativeLayout高度为100,宽度为200. - >不正确.
我意识到我可以在调用类中使用我的宽高比约束逻辑,它将放置RelativeLayout在第一位(同时我可能会这样做以解决这个问题),但实际上这是我想要的实现细节RelativeLayout本身就要表现.
澄清:我正在读回的合成宽度和高度值来自使用getWidth()和getHeight().在再次执行布局过程之后,将来某些时候会回读这些值.
Tre*_*vor 17
我已经解决这个现在还设置了width与height的LayoutParams目前由持有RelativeLayout中onMeasure().
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
// Restrict the aspect ratio to 1:1, fitting within original specified dimensions
int chosenDimension = Math.min(widthSize, heightSize);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST);
getLayoutParams().height = chosenDimension;
getLayoutParams().width = chosenDimension;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
Run Code Online (Sandbox Code Playgroud)
现在,这可以作为期望:对的大小RelativeLayout(以及后续调用getWidth()和getHeight())现在,在我的重写应用大小限制达成一致onMeasure().