1. 程式人生 > >Android動態設定控制元件座標

Android動態設定控制元件座標

程式碼:


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);
	}
}