Android--取得控件在手机屏幕上的位置
16lz
2021-01-23
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>
更多相关文章
- Android最新优秀而实用的开源组件1
- Android列表控件Spinner简单用法示例
- 高级控件1
- Android ImageView控件的MaxWidth、MaxHeight不起作用
- Android Jetpack架构组件Navigation管理Fragment框架
- android 圆形头像—— android开源系列:CircleImageView自定义圆
- android 概述 及四大组件
- Android 日期和时间选择控件的开发
- Android中自定义控件之飞入飞出布局及随机布局实现方式