方法一
在activity的onWindoFocusChanged中獲取寬高.此方法會被調用多次.在activity得到焦點或者失去焦點的時候均會調用.代碼如下
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus){
int width=testBtn.getMeasuredWidth();
int height=testBtn.getMeasuredHeight();
Log.d(TAG, "onWindowFocusChanged: width="+width);
Log.d(TAG, "onWindowFocusChanged: height="+height);
}
}
方法二
通過post將一個runnable投遞到消息隊列尾部
代碼如下:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_touch_test);
testBtn= findViewById(R.id.btn_test);
testBtn.post(new Runnable() {
@Override
public void run() {
int width=testBtn.getMeasuredWidth();
int height=testBtn.getMeasuredHeight();
Log.d(TAG, "onWindowFocusChanged: width="+width);
Log.d(TAG, "onWindowFocusChanged: height="+height);
}
});
}
方法三
ViewTreeObserver
使用ViewTreeObserver的眾多回調可以完成這個功能,比如使用onGlobalLayoutListener這個接口.當view樹發生改變,或者View樹內部的view的可見性發生改變時,此方法將被調用.此方法可能會被調用多次:
@Override
protected void onStart() {
super.onStart();
ViewTreeObserver viewTreeObserver=testBtn.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width=testBtn.getMeasuredWidth();
int height=testBtn.getMeasuredHeight();
Log.d(TAG, "onWindowFocusChanged: width="+width);
Log.d(TAG, "onWindowFocusChanged: height="+height);
}
});
}
方法四
手動調用view.measure 進行measure得到view的寬高.方法較復雜,此處不表
