获得控件坐标

三种方法:

  1. getLocationOnScreen(location):获得在屏幕上的坐标(包括通知栏)

  2. getLocationInWindow(location):获得在该窗口的坐标

  3. getTop()、getLeft()、getBottom()、getRight()获得在父窗口中的位置

   注意:在获得控件的宽高时,不能放在onCreate()中,在该方法中,是无法获得控件的宽高和坐标的,应在生命周期中的 onWindowFocusChanged(boolean hasFocus)方法中实现

  1. 以下代码仅供测试:


    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 {

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

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

    }

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>


你可能感兴趣的:(location,坐标,控件宽高)