第一种方法:
'''ViewTreeObserver vto2 = iv_mid_ad.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
iv_mid_ad.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mylog.e("height:"+iv_mid_ad.getHeight());
mylog.e("width:"+iv_mid_ad.getWidth());
}
});'''
第二种方法:
'''ViewTreeObserver vto =iv_mid_ad.getViewTreeObserver();
vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener() {
public booleanonPreDraw() {
intheight =iv_mid_ad.getMeasuredHeight();
intwidth =iv_mid_ad.getMeasuredWidth();
mylog.i("height:"+ height);
mylog.i("width:"+ width);
ViewGroup.LayoutParams layoutParams =iv_mid_ad.getLayoutParams();
layoutParams.width= width;
layoutParams.height= width /4;
iv_mid_ad.setLayoutParams(layoutParams);
return true;
}
});'''
总结:直接在oncreate中getwidth,getheight的值都会是0。ViewGroup.LayoutParams layoutParams =iv_mid_ad.getLayoutParams();中的layoutParams的width和height都是在xml中的值,如android:layout_width="150dp",不过值是px单位。 当然如果是wrap_content和match_parent的时候获取的值如下对应:
wrap_content 值为-2;
match_parent值为-1;
fill_parent值为-1.