Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 獲取控件大小和設置調整控件的位置XY示例

獲取控件大小和設置調整控件的位置XY示例

編輯:關於Android編程

網上很多人對設置控件的位置都使用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);
}
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved