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

  • 1
  • 2
  • 下一页

相关内容