??今天來簡(jiǎn)單的介紹一下怎么在Activity中拿到View的width和height。有人可能會(huì)疑問诫舅,這個(gè)有什么難的鲁森,我們直接可以在Activity生命周期函數(shù)里面獲取width和height÷蟮剑看似簡(jiǎn)單绿饵,實(shí)際上在onCreate、onStart瓶颠、onResume中均無法獲取正確的width和height拟赊,這是因?yàn)閂iew的measure過程和Activity的生命周期方法不是同步的,因此無法保證Activity執(zhí)行了onCreate粹淋、onStart吸祟、onResume時(shí),某個(gè)View已經(jīng)測(cè)量完畢桃移,如果View還沒有測(cè)量完畢的話屋匕,那么獲得的寬和高就是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這個(gè)方法的定義是:View已經(jīng)初始化完畢了借杰,width和height已經(jīng)準(zhǔn)備好了过吻,這個(gè)時(shí)候去獲取width和height是沒有問題的。需要注意的是:onWindowFocusChanged會(huì)調(diào)用多次蔗衡,當(dāng)Activity的窗口得到焦點(diǎn)和失去焦點(diǎn)時(shí)均會(huì)被調(diào)用一次纤虽。具體來說,當(dāng)Activity繼續(xù)執(zhí)行和暫停執(zhí)行時(shí)粘都,onWindowFocusChanged均會(huì)被調(diào)用廓推,如果頻繁的進(jìn)行onResume和onPause,那么onWindowFocusChanged也會(huì)被頻繁的調(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方法將一個(gè)runnable對(duì)象投遞到mButton的消息隊(duì)列的尾部樊展,然后等待Looper調(diào)用此runnable的時(shí)候,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)可以完成這個(gè)功能专缠,比如使用OnGlobalLayoutListener這個(gè)接口,當(dāng)View樹的狀態(tài)發(fā)生改變或者View內(nèi)部的View的可見性發(fā)生改變時(shí)淑仆,onGlobalLayout方法將被回調(diào)涝婉,因此這是獲取View的width和height一個(gè)很好的時(shí)機(jī)。需要注意的是蔗怠,伴隨著View樹的狀態(tài)改變等等墩弯,onGlobalLayout會(huì)被調(diào)用多次吩跋。