在activity生命周期方法:onCreate(),onStart(),onResume()中调用View.getWidth()和View.getHeight()方法获取View的高度是不可行的,因为此时布局没有加载是不可见状态。
创新互联建站专注于宜昌企业网站建设,响应式网站,商城系统网站开发。宜昌网站建设公司,为宜昌等地区提供建站服务。全流程按需求定制开发,专业设计,全程项目跟踪,创新互联建站专业和态度为您提供的服务
还有当view的可见状态为:GONE,时获取的宽高也是0;
2. 解决办法:
(1)直接测量:
private void first() { int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(width, height); int height1 = textView.getMeasuredHeight(); int width3 = textView.getMeasuredWidth(); System.out.println("first: 宽: " + width3 + " 高: " + height1); }
(2)添加绘制view之前的监听
private void second() { ViewTreeObserver vto = textView.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { int height = textView.getMeasuredHeight(); int width = textView.getMeasuredWidth(); System.out.println("second: 宽:" + width + " 高: " + height); return true; } }); }
(3)添加整体布局监听
private void third() { ViewTreeObserver vto = textView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { public void onGlobalLayout() { textView.getViewTreeObserver().removeGlobalOnLayoutListener( this); int height = textView.getMeasuredHeight(); int width = textView.getMeasuredWidth(); System.out.println("third: 宽:" + width + " 高: " + height); } }); }
网站题目:android——获取view的宽高
当前路径:https://www.cdcxhl.com/article18/jjoidp.html
成都网站建设公司_创新互联,为您提供域名注册、网站策划、网页设计公司、网站排名、商城网站、定制开发
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联