??今天來簡單的介紹一下怎么在Activity中拿到View的width和height。有人可能會疑問,這個有什么難的,我們直接可以在Activity生命周期函數(shù)里面獲取width和height??此坪唵?,實際上在onCreate、onStart、onResume中均無法獲取正確的width和height,這是因為View的measure過程和Activity的生命周期方法不是同步的,因此無法保證Activity執(zhí)行了onCreate、onStart、onResume時,某個View已經(jīng)測量完畢,如果View還沒有測量完畢的話,那么獲得的寬和高就是0.那么有什么方法來正確的獲取呢?
1.onWindowFoucusChanged
public class MainActivity extends AppCompatActivity {
private Button mButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.id_button);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
int width = mButton.getMeasuredWidth();
int height = mButton.getMeasuredHeight();
Log.i("main", "width = " + width + " height = " + height);
}
}
}
??onWindowFocusChanged這個方法的定義是:View已經(jīng)初始化完畢了,width和height已經(jīng)準備好了,這個時候去獲取width和height是沒有問題的。需要注意的是:onWindowFocusChanged會調(diào)用多次,當Activity的窗口得到焦點和失去焦點時均會被調(diào)用一次。具體來說,當Activity繼續(xù)執(zhí)行和暫停執(zhí)行時,onWindowFocusChanged均會被調(diào)用,如果頻繁的進行onResume和onPause,那么onWindowFocusChanged也會被頻繁的調(diào)用。
2.view.post(Runnable)
public class MainActivity extends AppCompatActivity {
private Button mButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.id_button);
mButton.post(new Runnable() {
@Override
public void run() {
int width = mButton.getMeasuredWidth();
int height = mButton.getMeasuredHeight();
Log.i("main", "width = " + width + " height = " + height);
}
});
}
}
??我們可以通過post方法將一個runnable對象投遞到mButton的消息隊列的尾部,然后等待Looper調(diào)用此runnable的時候,View已經(jīng)初始化好了。
3.ViewTreeObserver
public class MainActivity extends AppCompatActivity {
private Button mButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.id_button);
}
@Override
protected void onStart() {
super.onStart();
ViewTreeObserver viewTreeObserver = mButton.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int width = mButton.getMeasuredWidth();
int height = mButton.getMeasuredHeight();
}
});
}
}
??使用ViewTreeObsrever的眾多回調(diào)可以完成這個功能,比如使用OnGlobalLayoutListener這個接口,當View樹的狀態(tài)發(fā)生改變或者View內(nèi)部的View的可見性發(fā)生改變時,onGlobalLayout方法將被回調(diào),因此這是獲取View的width和height一個很好的時機。需要注意的是,伴隨著View樹的狀態(tài)改變等等,onGlobalLayout會被調(diào)用多次。