Android 获取控件的宽和高
来源:互联网 发布:linux 自启动 编辑:程序博客网 时间:2024/05/29 19:49
在onCreate()里面获取控件的高度view.getHeight()=0
因为,在onCreate(),我们的布局控件才会被度量(measure),所以我们在onCreate方法里面通过view.getHeight()获取控件的高度或者宽度肯定是0,因为它自己还没有被度量,也就是说他自己都不知道自己有多高,而你这时候去获取它的尺寸,肯定是不行的。
在网上找到了如下办法:
//------------------------------------------------方法一 int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); imageView.measure(w, h); int height =imageView.getMeasuredHeight(); int width =imageView.getMeasuredWidth(); Log.e("TAG","宽高"+height+","+width);//-----------------------------------------------方法二 ViewTreeObserver vto = imageView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = imageView.getMeasuredHeight(); int width = imageView.getMeasuredWidth(); Log.e("TAG","宽高"+height+","+width); return true; } }); //-----------------------------------------------方法三 ViewTreeObserver vto2 = imageView.getViewTreeObserver(); vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this); Log.e("TAG","宽高"+imageView.getHeight()+","+imageView.getWidth()); } });
1、方法一执行了三次测量, 比其他的两个方法多了一次计算,也就是多调用了一次onMeasure()方法,该方法虽然看上去简单,但是如果要目标控件计算耗时比较大的话(如listView等),不建议使用。
2、方法二执行了两次测量,但是如果将空间放在ScrollView 则会执行很多次,不建议使用。
3、方法三初始时执行两次,用着比较合适
阅读全文
0 0
- Android 获取Android控件的宽和高
- Android获取Android控件的宽和高
- Android 获取控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 获取Android控件的宽和高
- 【Android】获取控件的宽和高
- 【Android】获取控件的宽和高
- 获取Android控件的宽和高
- 编写程序实现文件的分布式存储
- Redis学习(二)redis配置
- EL表达式处理字符串 是否 包含 某字符串 截取 拆分...............
- solidThinking.Click2Form.2017.1.0.Win64 1DVD
- C#中的委托与事件
- Android 获取控件的宽和高
- PTA 3.11表达式转换
- 【非技术面试】31道,不准备就会掉进坑的问题
- HDU-1398 Square Coins
- WebView的基本使用
- 正则表达式
- Oracle connect by的使用
- 一些博客
- oracle 重启与关闭