Android获取view在屏幕中的位置

Android获取view在屏幕中的位置  

getLocalVisibleRect , 返回一个填充的Rect对象, 感觉是这个View的Rect大小,left,top取到的都是0


getGlobalVisibleRect , 获取全局坐标系的一个视图区域, 返回一个填充的Rect对象;该Rect是基于总整个屏幕的

getLocationOnScreen ,计算该视图在全局坐标系中的x,y值,(注意这个值是要从屏幕顶端算起,也就是索包括了通知栏的高度)//获取在当前屏幕内的绝对坐标 

getLocationInWindow ,计算该视图在它所在的widnow的坐标x,y值,//获取在整个窗口内的绝对坐标 (不是很理解= =、)

getLeft , getTopgetBottomgetRight,  这一组是获取相对在它父亲里的坐标


**注**:如果在Activity的OnCreate()事件输出那些参数,是全为0,要等UI控件都加载完了才能获取到这些,一般在onResume()方法或者触摸事件在可以获取到

example:

    int[] location = new int[2];
    v.getLocationOnScreen(location);
    int x = location[0];
    int y = location[1];


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值