三种方法:android
getLocationOnScreen(location):得到在屏幕上的坐标(包括通知栏)app
getLocationInWindow(location):得到在该窗口的坐标ide
getTop()、getLeft()、getBottom()、getRight()得到在父窗口中的位置测试
注意:在得到控件的宽高时,不能放在onCreate()中,在该方法中,是没法得到控件的宽高和坐标的,应在生命周期中的 onWindowFocusChanged(boolean hasFocus)方法中实现this
如下代码仅供测试:xml
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;生命周期
public class TestActivity extends Activity {utf-8
private ImageView img;
private RelativeLayout container;
private TextView show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageview);
img = (ImageView) findViewById(R.id.img);
container = (RelativeLayout) findViewById(R.id.container);
show = (TextView) findViewById(R.id.show);
}get
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
int[] location = new int[2];
img.getLocationInWindow(location);
View hView = new View(this);
hView.setBackgroundColor(Color.WHITE);
LayoutParams lp= new LayoutParams(5, location[1]+img.getHeight());
lp.leftMargin = location[1]+img.getWidth()+20;
lp.topMargin = img.getTop();
hView.setLayoutParams(lp);
container.addView(hView);
show.setText("x:"+location[0]+"\ny:"+img.getTop());
} it
}
imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:src="@drawable/home1" />
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/img" />
</RelativeLayout>