android

测量控件的宽高,并按照测量的结果重新修改

2017-11-17  本文已影响6人  二毛_coder

第一种方法:

'''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.

上一篇 下一篇

猜你喜欢

热点阅读