android 如何获取LinearLayout的宽度和高度?

由于Android程序的运行机制决定了无法再组件类外部使用getWidth和getHeight方法获得高度和宽度(在自定义组件类中可以实现),必须使用View.getMeasuredWidth和View.getMeasureHeight方法获得当前组件的宽度和高度,在调用这两个方法之前,必须调用View.measure方法先测量组件宽度和高度。
如果想直接获取在布局文件中定义的组件的宽度和高度,可以直接使用View.getLayoutParams().width和View.getLayoutParams().height

代码如下:

[java]  view plain  copy
  1. View view = getLayoutInflater().inflate(R.layout.activity_main, null);  
  2. LinearLayout linearlayout = (LinearLayout)view.findViewById(R.id.linearlayout);  
  3. //measure方法的参数值都设为0即可  
  4. linearlayout.measure(0,0);  
  5. //获取组件宽度  
  6. int width = linearlayout.getMeasuredWidth();  
  7. //获取组件高度  
  8. int height = linearlayout.getMeasuredHeight();  

猜你喜欢

转载自blog.csdn.net/canduecho/article/details/78902660