欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

获取控件大小和设置调整控件的位置XY示例

程序员文章站 2023-08-12 19:02:30
网上很多人对设置控件的位置都使用view.setpadding(left, top, right, bottom) ,其实这玩意很差劲,它是设置自己本身位置的偏移,我们很少...
网上很多人对设置控件的位置都使用view.setpadding(left, top, right, bottom) ,其实这玩意很差劲,它是设置自己本身位置的偏移,我们很少需要这种效果,我需要的设置控件相对屏幕左上角的x 、y位置。众里寻他千百度,蓦然回首,那人却在灯火阑珊处!
复制代码 代码如下:

import android.view.view;
import android.view.viewgroup.marginlayoutparams;
import android.widget.relativelayout;
/*
* 获取、设置控件信息
*/
public class widgetcontroller {
/*
* 获取控件宽
*/
public static int getwidth(view view)
{
int w = view.measurespec.makemeasurespec(0,view.measurespec.unspecified);
int h = view.measurespec.makemeasurespec(0,view.measurespec.unspecified);
view.measure(w, h);
return (view.getmeasuredwidth());
}
/*
* 获取控件高
*/
public static int getheight(view view)
{
int w = view.measurespec.makemeasurespec(0,view.measurespec.unspecified);
int h = view.measurespec.makemeasurespec(0,view.measurespec.unspecified);
view.measure(w, h);
return (view.getmeasuredheight());
}

/*
* 设置控件所在的位置x,并且不改变宽高,
* x为绝对位置,此时y可能归0
*/
public static void setlayoutx(view view,int x)
{
marginlayoutparams margin=new marginlayoutparams(view.getlayoutparams());
margin.setmargins(x,margin.topmargin, x+margin.width, margin.bottommargin);
relativelayout.layoutparams layoutparams = new relativelayout.layoutparams(margin);
view.setlayoutparams(layoutparams);
}
/*
* 设置控件所在的位置y,并且不改变宽高,
* y为绝对位置,此时x可能归0
*/
public static void setlayouty(view view,int y)
{
marginlayoutparams margin=new marginlayoutparams(view.getlayoutparams());
margin.setmargins(margin.leftmargin,y, margin.rightmargin, y+margin.height);
relativelayout.layoutparams layoutparams = new relativelayout.layoutparams(margin);
view.setlayoutparams(layoutparams);
}
/*
* 设置控件所在的位置yy,并且不改变宽高,
* xy为绝对位置
*/
public static void setlayout(view view,int x,int y)
{
marginlayoutparams margin=new marginlayoutparams(view.getlayoutparams());
margin.setmargins(x,y, x+margin.width, y+margin.height);
relativelayout.layoutparams layoutparams = new relativelayout.layoutparams(margin);
view.setlayoutparams(layoutparams);
}
}