Many people on the internet use view to set controls. setPadding (left, top, right, bottom) is actually a bad thing. It is used to set the offset of its own position. We seldom need this effect, set the position of the control relative to X and Y in the upper left corner of the screen. The crowd looked for him and looked back, but the man was in the dark!
Copy codeThe Code is as follows: import android. view. View;
Import android. view. ViewGroup. MarginLayoutParams;
Import android. widget. RelativeLayout;
/*
* Obtain and set control information
*/
Public class WidgetController {
/*
* Obtain the control width.
*/
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 ());
}
/*
* Control height
*/
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 ());
}
/*
* Set the position X of the control without changing the width and height,
* X is the absolute position. In this case, Y may return to 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 );
}
/*
* Set the position Y of the control without changing the width and height,
* Y indicates the absolute position. In this case, X may return to 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 );
}
/*
* Set the position of the control to YY without changing the width and height,
* XY is the absolute position.
*/
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 );
}
}