Android獲取view高度的三種方式
本文為大家分享了Android獲取view高度的方法,供大家參考,具體內(nèi)容如下
getMeasuredHeight()與getHeight的區(qū)別
實(shí)際上在當(dāng)屏幕可以包裹內(nèi)容的時(shí)候,他們的值相等,
只有當(dāng)view超出屏幕后,才能看出他們的區(qū)別:
getMeasuredHeight()是實(shí)際View的大小,與屏幕無關(guān),
而getHeight的大小此時(shí)則是屏幕的大小。
當(dāng)超出屏幕后,getMeasuredHeight()等于getHeight()加上屏幕之外沒有顯示的大小
具體方法
我們知道在oncreate中View.getWidth和View.getHeight無法獲得一個(gè)view的高度和寬度,這是因?yàn)閂iew組件 布局要在onResume回調(diào)后完成。
下面說三種方式
getViewTreeObserver
使用 getViewTreeObserver().addOnGlobalLayoutListener()來獲得寬度或者高度。
OnGlobalLayoutListener 是ViewTreeObserver的內(nèi)部類,當(dāng)一個(gè)視圖樹的布局發(fā)生改變時(shí),可以被ViewTreeObserver監(jiān)聽到,這是一個(gè)注冊(cè)監(jiān)聽視圖樹的觀察者(observer),在視圖樹的全局事件改變時(shí)得到通知。ViewTreeObserver不能直接實(shí)例化,而是通過getViewTreeObserver()獲得。
除了OnGlobalLayoutListener ,ViewTreeObserver還有如下內(nèi)部類:
interfaceViewTreeObserver.OnGlobalFocusChangeListener
當(dāng)在一個(gè)視圖樹中的焦點(diǎn)狀態(tài)發(fā)生改變時(shí),所要調(diào)用的回調(diào)函數(shù)的接口類
interfaceViewTreeObserver.OnGlobalLayoutListener
當(dāng)在一個(gè)視圖樹中全局布局發(fā)生改變或者視圖樹中的某個(gè)視圖的可視狀態(tài)發(fā)生改變時(shí),所要調(diào)用的回調(diào)函數(shù)的接口類
interfaceViewTreeObserver.OnPreDrawListener
當(dāng)一個(gè)視圖樹將要繪制時(shí),所要調(diào)用的回調(diào)函數(shù)的接口類
interfaceViewTreeObserver.OnScrollChangedListener
當(dāng)一個(gè)視圖樹中的一些組件發(fā)生滾動(dòng)時(shí),所要調(diào)用的回調(diào)函數(shù)的接口類
interfaceViewTreeObserver.OnTouchModeChangeListener
當(dāng)一個(gè)視圖樹的觸摸模式發(fā)生改變時(shí),所要調(diào)用的回調(diào)函數(shù)的接口類
其中,我們可以利用OnGlobalLayoutListener來獲得一個(gè)視圖的真實(shí)高度。
private int mHeaderViewHeight;
private View mHeaderView;
.....
mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mHeaderViewHeight = mHeaderView.getHeight();
mHeaderView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});
但是需要注意的是OnGlobalLayoutListener可能會(huì)被多次觸發(fā),因此在得到了高度之后,要將OnGlobalLayoutListener注銷掉。
View post事件中獲取
還可以在VIew的post方法中獲取
public class TestHeight extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
tv = (TextView) findViewById(R.id.textView);
tv.post(new Runnable() {
@Override
public void run() {
int height= tv.getHeight();
}
});
}
}
直接測(cè)量計(jì)算
int intw=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int inth=View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); textView.measure(intw, inth); int intwidth = textView.getMeasuredWidth(); int intheight = textView.getMeasuredHeight();
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android TextSwitcher文本切換器和ViewFlipper使用詳解
這篇文章主要為大家詳細(xì)介紹了Android TextSwitcher文本切換器和ViewFlipper的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
Android HTTP網(wǎng)絡(luò)請(qǐng)求的異步實(shí)現(xiàn)
這篇文章主要介紹了Android HTTP網(wǎng)絡(luò)請(qǐng)求的異步實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2016-07-07

