首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

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

2013-02-19 
Android--取得控件在手机屏幕上的位置import android.app.Activityimport android.os.Bundleimport andr

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

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>


 

热点排行