android——获取view的宽高
在activity生命周期方法:onCreate(),onStart(),onResume()中调用View.getWidth()和View.getHeight()方法获取View的高度是不可行的,因为此时布局没有加载是不可见状态。
还有当view的可见状态为:GONE,时获取的宽高也是0;
2. 解决办法:
(1)直接测量:
privatevoidfirst(){intwidth=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);intheight=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);textView.measure(width,height);intheight1=textView.getMeasuredHeight();intwidth3=textView.getMeasuredWidth();System.out.println("first:宽:"+width3+"高:"+height1);}
(2)添加绘制view之前的监听
privatevoidsecond(){ViewTreeObservervto=textView.getViewTreeObserver();vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener(){publicbooleanonPreDraw(){intheight=textView.getMeasuredHeight();intwidth=textView.getMeasuredWidth();System.out.println("second:宽:"+width+"高:"+height);returntrue;}});}
(3)添加整体布局监听
privatevoidthird(){ViewTreeObservervto=textView.getViewTreeObserver();vto.addOnGlobalLayoutListener(newOnGlobalLayoutListener(){publicvoidonGlobalLayout(){textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);intheight=textView.getMeasuredHeight();intwidth=textView.getMeasuredWidth();System.out.println("third:宽:"+width+"高:"+height);}});}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。