2012-06-01 65 views
2

我有像這樣的嵌套視圖V自定義佈局: 的LinearLayout L1 --->的LinearLayout L2 --->查看V.Android:對於嵌套視圖,什麼是getX()和gety()相對於?

我有註冊V.上的觸摸事件的OnTouchListener,我需要以獲得觸摸事件相對於視圖邊緣的座標V.

event.getX()和event.getY()返回的值是什麼?我一直在搜索並看到衝突的聲明,有人說這些值已經相對於視圖V的邊緣,但另一些人說我需要從event.getX()和event.getY()減去視圖V的邊緣座標以獲得相對座標。

感謝您的幫助。

回答

5

從谷歌的文檔

的getX()方法:

這種觀點的視覺x位置,以像素爲單位。這相當於 translationX屬性加上當前的左側屬性。

setTranslationX()方法:

設置此視圖相對的水平位置,以它的左 位置。這可以有效地將對象佈局後的對象放置在 以外的任何位置,除此之外對象的佈局放置它。

getLeft()方法:該視圖相對於其父的

左側位置。

因此,的getX()返回視圖的水平相對於其父位置。

UPDATE:

對於event.getX()相對於父母,你得到的結果是也。 您可以通過放置一個按鈕,水平居中一個RelativeLayout的內部做一個簡單的測試和檢查值當您單擊按鈕

在你的佈局XML:

<RelativeLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:layout_centerHorizontal="true"> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button" /> 

</RelativeLayout> 

在你的活動:

mBtn = ((Button) findViewById(R.id.button1)); 
    mBtn.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      Log.d("", "getX = " + event.getX()); 
      return false; 
     } 
    }); 

如果您單擊左邊距上的按鈕,您將得到一個接近0.0的值。

+3

實際上,我的問題是event.getX()和event.getY()是相對的,抱歉,如果不清楚的話。我編輯了我的問題。 – Mayank

+0

查看已更新的答案 –

+0

工作,謝謝。 – Mayank

相關問題