我创建了自定义可绘制对象。为了绘制它,我使用了边界。但是,当用户使用时:
android:layout_width="match_parent"
android:layout_height="wrap_content"
我得到bounds.height()==1。然后,我想使用高度= 0.8 * bounds.width。
我尝试了它,因为当用户使用WRAP_CONTENT时,我得到bounds.height()=1。因此,我将可绘制高度设置为0.8 * width()。但是我没有合适的尺码。我刚好知道高度为1。我读到您需要调用invalidate(),但是如何调用它,因为如果我在 draw()中调用invalidate(),则该方法将被调用无限地。
答案 0 :(得分:2)
您应该使用onMeasure方法。
生命周期在需要使正在处理的视图大小无效时调用它。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
ViewGroup.LayoutParams params = getLayoutParams();
//height and width expected from wrap_content and match_parent
int newHeight = MeasureSpec.getSize(heightMeasureSpec);
int newWidth = MeasureSpec.getSize(widthMeasureSpec);
int myHeight= newWidth * 0.8;
height = myHeight
width = newWidth
}
答案 1 :(得分:1)
考虑使用layout_constraintDimensionRatio
中的ConstraintLayout
:
Official Guide
或者您也可以在onMeasure()
中解决尺寸问题。