三種方法: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>