2013-10-28 15 views
0

我想在RelativeLayout中的特定位置上設置我的EditTest。所以我得到Ediitext的位置,並根據我想要的設置。這對我來說工作得很好。但是當Android 2.2和android 2.3設備沒有找到getY()方法時會出現問題。因爲我想獲得Ediitext的位置。如何獲取EditText在RelativeLayout中的位置或替代方法getY()

現在我需要找到另一種方法,因爲它不適用於2.2和2.3。

這裏是我的代碼供參考。

ViewTreeObserver autoCompleteObserver = myAutoComplete.getViewTreeObserver(); 
    autoCompleteObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 

     @Override 
     public void onGlobalLayout() {    
      relativeLayoutHeight = ((int) myAutoComplete.getY()-12); 
     } 
    }); 

activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight(); 
      Log.i("TEST", "GLOBAL LAYOUT "+activityRootView.getHeight()); 
      Log.i("TEST", "GLOBAL LAYOUT rel"+relativeLayoutHeight); 
      if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard... 
       Log.i("TEsT","Keyboard visible"); 
       myRelativLayout.scrollTo(0, relativeLayoutHeight); 
      } 
      else 
      { 
       Log.i("TEsT","Keyboard not visible"); 
       myRelativLayout.scrollTo(0, 0); 
       myAutoComplete.setDropDownHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 
      } 
     } 
    }); 
} 

這段代碼在4.1工作正常,但我需要找到另一種方法爲getY()這回我的EditText的位置。
給我任何參考或提示。

+0

View.getTop()? – Blackbelt

回答

2

有在搭載Android 4.1一起來看看從View類getY()方法:Link

/** 
* The visual y position of this view, in pixels. This is equivalent to the 
* 'translationY' property plus the current 
* 'top' property. 
* 
* @return The visual y position of this view, in pixels. 
*/ 

public float getY() { 
    return mTop + 
      (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 
} 

在Android 2.2 & 2.3,有一個名爲類似的方法getTop()Link

/** 
* Top position of this view relative to its parent. 
* 
* @return The top of this view, in pixels. 
*/ 

public final int getTop() { 
    return mTop; 
} 

因此,如果您沒有對您的EditText應用任何翻譯(使用View#setTranslationY(float)等),getY()getTop()將提供基本相同的結果。

1

在代碼里加入您的onGlobalLayout

int[] locations = new int[2]; 
yourView.getLocationOnScreen(locations); 
int x = locations[0]; 
int y = locations[1];//returns Y position 
+0

它不起作用 –

+0

什麼是錯誤? – Naddy

+0

沒有錯誤。但是當我使用getY();然後它顯示在正確的位置編輯文本,但如果我使用此代碼,那麼它將在一個屏幕上顯示良好,但它不會顯示正確的其他碎片。意味着沒有兼容性。 –