Gets the control size and sets the location of the resize control XY example

  • 2020-05-10 18:51:09
  • OfStack

A lot of people on the web use view.setPadding (left, top, right, bottom) to set the position of the control, which is really bad. Look for him in the crowd, suddenly look back, that person is in the lights dim!
 
import android.view.View; 
import android.view.ViewGroup.MarginLayoutParams; 
import android.widget.RelativeLayout; 
/* 
*  Gets and sets control information  
*/ 
public class WidgetController { 
/* 
*  Get 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()); 
} 
/* 
*  Get 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()); 
} 

/* 
*  Sets the location of the control X And without changing the width and height,  
* X Is the absolute position, at this point Y May return 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); 
} 
/* 
*  Sets the location of the control Y And without changing the width and height,  
* Y Is the absolute position, at this point X May return 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); 
} 
/* 
*  Sets the location of the control YY And 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); 
} 
} 

Related articles: