如果是自定义的View(java文件),如何动态改变它的大小
时间: 2024-03-11 21:49:31 浏览: 31
如果要动态改变自定义 View 的大小,可以在自定义 View 中覆盖 `onMeasure()` 方法,在该方法中重新计算 View 的大小。具体来说,我们可以根据需要改变的宽度和高度,调用 `setMeasuredDimension()` 方法来设置 View 的新宽度和高度。
例如,假设我们有一个自定义 View 类 `MyView`,我们要在运行时将其宽度设置为父容器宽度的一半,高度不变。我们可以按照以下步骤操作:
1. 在 `MyView` 类中覆盖 `onMeasure()` 方法,并在其中计算新的宽度和高度:
```java
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int newWidth = parentWidth / 2; // 新的宽度为父容器宽度的一半
int newHeight = parentHeight; // 高度不变
int newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth, MeasureSpec.EXACTLY);
int newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight, MeasureSpec.EXACTLY);
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec);
}
```
在 `onMeasure()` 方法中,我们首先获取父容器的宽度和高度。然后,我们计算新的宽度和高度,将宽度设置为父容器宽度的一半,高度不变。最后,我们使用 `MeasureSpec.makeMeasureSpec()` 方法创建新的宽度和高度的测量规格,并调用 `setMeasuredDimension()` 方法设置 View 的新宽度和高度。
2. 在布局文件中使用 `MyView`:
```xml
<com.example.MyView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
```
通过上述步骤,我们就可以在运行时动态改变 `MyView` 的大小了。当其所在的父容器大小改变时,`onMeasure()` 方法会被调用,从而重新计算新的宽度和高度,并更新 View 的大小。