0

我正在尝试将我的 EditTest 设置在 RelativeLayout 中的特定位置。所以我得到了 Ediitext 的位置并根据我想要的设置。它对我很好。但是当 Android 2.2 和 android 2.3 设备没有找到getY()方法时就会出现问题。因为我想获得 Ediitext 的位置。

现在我需要为此找到另一种方法,因为它在 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 位置的替代方法。
给我任何参考或提示。

4

2 回答 2

2

Have a look at the getY() method from View class in android 4.1: 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);
}

On Android 2.2 & 2.3, there's a similar method called 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;
}

So, if you are not applying any translations to your EditText (using View#setTranslationY(float) etc.), getY() and getTop() will provide essentially the same result.

于 2013-11-16T19:08:46.610 回答
1

将此代码添加到您的onGlobalLayout

int[] locations = new int[2];
yourView.getLocationOnScreen(locations);
int x = locations[0];
int y = locations[1];//returns Y position
于 2013-10-28T10:50:37.047 回答