Android笔记:测量控件宽高和动态设置控件宽高

1.测算控件宽高

 初始化UI时,无法直接通过getWidth()或getHeight()获取到控件的宽度或高度。可采用定时测算去获取控件的宽度/高度,方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//每隔10毫秒测算一次宽度,直到测算完毕
mMeasureAction =  new  Runnable()
{
     @Override
     public  void  run()
     {
         if  (mLayout_map.getWidth() !=  0 )
         {
             Log.i( "w" , mLayout_map.getWidth() +  "" );
             Log.i( "h" , mLayout_map.getHeight() +  "" );
        }
         else
         {
             mLayout_map.postDelayed(mMeasureAction,  10 );
         }
     }
};
mLayout_map.postDelayed(mMeasureAction,  10 );


参考资料:http://blog.163.com/zhaolin53636848@126/blog/static/490866682012065373798/



2.动态修改控件的宽高

  比如,将imageview的宽度改为200,高度改为宽度的3/4。其中RelativeLayout是imageview的父布局,方法如下:

1
import  android.widget.RelativeLayout.LayoutParams;


1
2
3
4
5
6
int  imgWeight =  200 ;
RelativeLayout.LayoutParams sp_params =  new  RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
sp_params.width = imgWeight;
sp_params.height = imgWeight *  3  / 4  ;
imageView.setLayoutParams(sp_params);





本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1358564,如需转载请自行联系原作者

你可能感兴趣的:(Android笔记:测量控件宽高和动态设置控件宽高)