在Activity中获取View的高度(Android开发艺术探索学习笔记)
来源:互联网 发布:如何上淘宝网购到付款 编辑:程序博客网 时间:2024/06/06 04:28
在onCreate里面,你是无法获得长宽值的,始终为0,为什么会这样呢?因为View的measure过程和Activity的生命周期不是同步的。所以下面来讨论一下在Activity中获取View的高度几种方法。
1.onWindowFocusChanged()
这个方法在onResume()和onPause()也会被调用,如果onResume()和onPause()被频繁调用,那么onWindowFocusChanged()也会被频繁调用。
/** * Called when the current {@link Window} of the activity gains or loses * focus. This is the best indicator of whether this activity is visible * to the user. The default implementation clears the key tracking * state, so should always be called. * …… */ public void onWindowFocusChanged(boolean hasFocus) { }
2.View.post()
通过post将一个Runnable投递到消息队列尾部。等Runnable被调用的时候,View已经初始化好了。
/** * <p>Causes the Runnable to be added to the message queue. * The runnable will be run on the user interface thread.</p> */ public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; }
3.ViewTreeObserver
使用OnGlobalLayoutListener(),监听布局完成,但是会多次调用,所以要及时remove掉Listener。
final ViewTreeObserver viewTreeObserver = mView.getViewTreeObserver(); viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { viewTreeObserver .removeOnLayoutChangeListener(this); } });
类似的还有使用OnDrawListener()和OnPreDrawListener。
4.直接使用measure()
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); mView.measure(w, h); int height = mView.getMeasuredHeight(); int width = mView.getMeasuredWidth(); System.out.println("measure width=" + width + " height=" + height);
1 0
- 在Activity中获取View的高度(Android开发艺术探索学习笔记)
- Android 开发艺术探索 学习笔记 Activity
- **读Android开发艺术探索学习笔记--Activity的生命周期**
- Activity的启动过程(Android开发艺术探索学习笔记)
- Android开发艺术探索笔记(8)- View的基础
- Android开发艺术探索笔记(9)- View的滑动
- 《Android开发艺术探索》笔记(View的知识体系)
- Android开发艺术探索笔记(1)- Activity的生命周期
- Android开发艺术探索学习笔记(3)--View的事件体系(1)
- 《Android开发艺术探索》之学习笔记(四)View的工作原理
- 《Android开发艺术探索》之学习笔记(三)View的基础知识
- View的事件分发机制(Android开发艺术探索学习笔记)
- View的绘制流程源码分析(Android开发艺术探索学习笔记)
- 《Android开发艺术探索》之学习笔记(一)Activity的生命周期和启动模式
- 《Android开发艺术探索》学习笔记---Activity详解
- android 艺术开发探索 view移动 笔记
- Android开发艺术探索笔记 第一章Activity
- Android开发艺术探索笔记之Activity
- localhost 拒绝访问链接请求
- wamp图标橙色mysql不启动【错误解决】本地计算机上的mysql服务启动停止后,某些服务在未由其他服务或程序使用时将自动停止
- MYSQL触发器入门
- JVM学习笔记之一:体系结构
- unity中htc vive射线与UI碰撞检测-graphcs.Raycast()
- 在Activity中获取View的高度(Android开发艺术探索学习笔记)
- js前台图片回显
- 利用JDBC连接Oracle数据库
- hdu3037 隔板法+Lucas定理求大组合取模
- Apple本地认证(密码+Touch id)
- springboot+shiro+mybatis实现角色权限控制
- Linux下二进制文件安装MySQL
- Mysql Binlog日志模式的介绍与分析
- 免费的论文查重网站