android 获得组件宽度,android 中如何获取控件的宽和高
时间: 2024-01-22 18:20:46 浏览: 33
你可以使用以下方法获取 Android 中组件的宽度和高度:
1. 通过 View 对象的 getWidth() 和 getHeight() 方法获取组件的宽度和高度。
```java
View view = findViewById(R.id.view_id);
int width = view.getWidth();
int height = view.getHeight();
```
注意:在使用这种方法之前,确保该 View 已经被绘制完成。
2. 通过 ViewTreeObserver 对象的 addOnGlobalLayoutListener() 方法监听 View 的布局变化,并在回调方法中获取 View 的宽度和高度。
```java
final View view = findViewById(R.id.view_id);
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = view.getWidth();
int height = view.getHeight();
// do something with width and height
// remove the listener to avoid multiple callbacks
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
```
这种方法可以在 View 的布局变化时及时获取它的宽度和高度,但需要注意及时移除监听器,避免多次回调。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)