您的位置:首页 > 移动开发 > Android开发

Android--取得控件在手机屏幕上的位置

2013-02-16 16:15 295 查看
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

/**
* 如果在Activity的OnCreate()事件输出控件位置数据,是全为0,要等UI控件都加载完了才能获取到数据。
* @author ZLQ
*
*/
public class GetLocationData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

/*
* 单击按钮事件
*/
public void click(View v){
View view = findViewById(R.id.button2);
//数组长度必须为2
int[] locations = new int[2];
view.getLocationOnScreen(locations);
int x = locations[0];//获取组件当前位置的横坐标
int y = locations[1];//获取组件当前位置的纵坐标
Log.i("System.out", "x:" + x + "y:" + y);
}
}


 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<Button
android:id="@+id/button2"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="150dp"
android:onClick="click"
android:text="Button" />

</RelativeLayout>


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息