代码动态设置View的位置

网上很多人对设置控件的位置都使用view.setPadding(left, top, right, bottom) ,其实这玩意很差劲,它是设置自己本身位置的偏移,我们很少需要这种效果,我需要的设置控件相对屏幕左上角的X 、Y位置

/*

*获取、设置控件信息

*/

public classWidgetController {

/*

*获取控件宽

*/

public static intgetWidth(View view) {

intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

view.measure(w, h);

return(view.getMeasuredWidth());

}

/*

*获取控件高

*/

public static intgetHeight(View view) {

intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

view.measure(w, h);

return(view.getMeasuredHeight());

}

/*

*设置控件所在的位置X,并且不改变宽高,

* X为绝对位置,此时Y可能归0

*/

public static voidsetLayoutX(View view,intx) {

MarginLayoutParams margin =newMarginLayoutParams(view.getLayoutParams());

margin.setMargins(x, margin.topMargin, x + margin.width, margin.bottomMargin);

RelativeLayout.LayoutParams layoutParams =newRelativeLayout.LayoutParams(margin);

view.setLayoutParams(layoutParams);

}

/*

*设置控件所在的位置Y,并且不改变宽高,

* Y为绝对位置,此时X可能归0

*/

public static voidsetLayoutY(View view,inty) {

MarginLayoutParams margin =newMarginLayoutParams(view.getLayoutParams());

margin.setMargins(margin.leftMargin, y, margin.rightMargin, y + margin.height);

RelativeLayout.LayoutParams layoutParams =newRelativeLayout.LayoutParams(margin);

view.setLayoutParams(layoutParams);

}

/*

*设置控件所在的位置YY,并且不改变宽高,

* XY为绝对位置

*/

public static voidsetLayout(View view,intx,inty) {

MarginLayoutParams margin =newMarginLayoutParams(view.getLayoutParams());

margin.setMargins(x, y, x + margin.width, y + margin.height);

RelativeLayout.LayoutParams layoutParams =newRelativeLayout.LayoutParams(margin);

view.setLayoutParams(layoutParams);

}

}

你可能感兴趣的:(代码动态设置View的位置)