get Location In View - Android User Interface

Android examples for User Interface:View Position

Description

get Location In View

Demo Code


//package com.java2s;
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;

public class Main {
    public static Rect getLocationInView(View parent, View child) {
        if (child == null || parent == null) {
            throw new IllegalArgumentException(
                    "parent and child can not be null .");
        }/*from  ww  w . ja va  2  s  .com*/

        View decorView = null;
        Context context = child.getContext();
        if (context instanceof Activity) {
            decorView = ((Activity) context).getWindow().getDecorView();
        }

        Rect result = new Rect();
        Rect tmpRect = new Rect();

        View tmp = child;

        if (child == parent) {
            child.getHitRect(result);
            return result;
        }
        while (tmp != decorView && tmp != parent) {
            tmp.getHitRect(tmpRect);

            result.left += tmpRect.left;
            result.top += tmpRect.top;
            tmp = (View) tmp.getParent();
        }
        result.right = result.left + child.getMeasuredWidth();
        result.bottom = result.top + child.getMeasuredHeight();
        return result;
    }
}

Related Tutorials