Get location of view relative to application content (so no status bar and title bar). - Android User Interface

Android examples for User Interface:View

Description

Get location of view relative to application content (so no status bar and title bar).

Demo Code


//package com.java2s;

import android.graphics.Point;
import android.graphics.Rect;

import android.view.View;

import android.view.Window;

public class Main {
    private static Rect mStatusBarRect = new Rect();
    private static int[] mLocation = new int[2];

    /**/*from w  w w.  j  av a 2  s  .  c  om*/
     * Get location of view relative to application content (so no status bar and title bar).<br>
     * <br>
     * <b>Note</b>: Call this when content is completely inflated. So {@code onCreate} of an
     * activity won't work.
     * 
     * @param view
     *            any view which is attached to the content
     * 
     * @return location pixel
     */
    public static Point getContentLocation(View view) {
        Point point = getScreenLocation(view);
        point.y -= getContentOffsetFromTop(view);
        return point;
    }

    /**
     * Get location of view relative to screen.<br>
     * <br>
     * <b>Note</b>: Call this when content is completely inflated. So {@code onCreate} of an
     * activity won't work.
     * 
     * @param view
     *            any view which is attached to the content
     * 
     * @return location pixel
     */
    public static Point getScreenLocation(View view) {
        view.getLocationOnScreen(mLocation);
        return new Point(mLocation[0], mLocation[1]);
    }

    /**
     * Get offset of application content from top (so status bar + title bar).<br>
     * <br>
     * <b>Note</b>: Call this when content is completely inflated. So {@code onCreate} of an
     * activity won't work.
     * 
     * @param view
     *            any view which is attached to the content
     * 
     * @return offset to top in pixel
     */
    public static int getContentOffsetFromTop(View view) {
        int offset = view.getRootView()
                .findViewById(Window.ID_ANDROID_CONTENT).getTop();

        if (offset == 0) {
            view.getWindowVisibleDisplayFrame(mStatusBarRect);
            offset = mStatusBarRect.top;
        }

        return offset;
    }
}

Related Tutorials