歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:取得控件在手機屏幕上的位置

Android開發教程:取得控件在手機屏幕上的位置

日期:2017/3/1 10:01:37   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved