2014-10-08 82 views
1

我有一个问题,获取图像视图的顶部和左侧的位置。获取图像视图位置与包装容器可绘制图像

我的图像视图设置在相对布局的中心。 当我使用getleft()getTop()的结果对我来说是0和0

我的布局文件是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/rlMain" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:scaleType="center" 
     android:src="@drawable/ic_launcher" /> 

</RelativeLayout> 

这是真的急了我。

我的问题:

我写了一个代码,移动和缩放图像视图和工作正常,但在第一次点击,图像视图位置改变到0,0和我想的默认位置为防止在第一个变化单击。

+0

向我们展示你当前的代码?你什么时候调用'getLeft()'和'getTop()'? – Malvin 2014-10-08 07:14:50

+0

我通过id定义了我的图像视图并希望吐司它的位置,我如何在api level 8上敬酒图像视图位置? – 2014-10-08 07:23:54

+0

您是否在onCreate中调用'getLeft()'和'getTop()'? – Malvin 2014-10-08 07:25:05

回答

1

不知道如果我得到你的意思,但你可以尝试:

ImageView img = (ImageView) findViewById(R.id.image_view); 
img.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener(){ 

       @Override 
       public void onGlobalLayout() { 

        int left = img.getLeft(); 
        int top = img.getTop(); 
        //Toast the height and top... 
       } 

      }); 

由于图像会没有尚未呈现到onCreate屏幕,因此你总是会得到0,当你调用getLeft()getTop()

更多解释here

编辑

设置布局宽度和ImageView的高度为wrap_content

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/rlMain" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:scaleType="center" 
     android:src="@drawable/ic_launcher" /> 

</RelativeLayout> 
+0

谢谢,但我的问题仍然存在,我的imageview是在屏幕的中心,但左和顶部返回零.. – 2014-10-08 07:31:47

+0

我们可以看到你的xml布局代码? – Malvin 2014-10-08 07:34:04

+0

是的,让我编辑我的帖子 – 2014-10-08 07:35:19

0

int location [] = new int [2];

rlBoard.getLocationOnScreen(location);

您还可以使用的ImageView的的getX和的getY方法,但这种方法从API作品11

+0

谢谢你可以描述这段代码?我不使用它! – 2014-10-08 06:50:32

+0

rlBoard是相对布局对象,位置是整型数组和方法getLocatiOnScreen在屏幕上用相对布局中心填充数组 – 2014-10-08 06:54:51

+0

再次感谢,我的问题仍然存在!我使用api 8,不能在运行时获取图像视图对象位置... :( – 2014-10-08 07:02:48