新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
android——獲取view的寬高
在activity生命周期方法:onCreate(),onStart(),onResume()中調(diào)用View.getWidth()和View.getHeight()方法獲取View的高度是不可行的,因?yàn)榇藭r布局沒有加載是不可見狀態(tài)。
創(chuàng)新互聯(lián)建站專注于宜昌企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站,商城系統(tǒng)網(wǎng)站開發(fā)。宜昌網(wǎng)站建設(shè)公司,為宜昌等地區(qū)提供建站服務(wù)。全流程按需求定制開發(fā),專業(yè)設(shè)計,全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專業(yè)和態(tài)度為您提供的服務(wù)
還有當(dāng)view的可見狀態(tài)為: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之前的監(jiān)聽
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)添加整體布局監(jiān)聽
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的寬高
文章位置:http://fisionsoft.com.cn/article/jjoidp.html