2014-10-08 27 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