position Relative Layout Child To Top Right Of View - Android User Interface

Android examples for User Interface:Layout

Description

position Relative Layout Child To Top Right Of View

Demo Code


//package com.java2s;

import android.graphics.Rect;

import android.view.View;
import android.view.ViewGroup;

public class Main {
    public static void positionRelativeLayoutChildToTopRightOfView(
            View child, View view) {
        Rect viewLocation = getViewLocationRelativeTo(view,
                (View) child.getParent());

        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) child
                .getLayoutParams();// w w  w . jav a2s .c  o m
        params.leftMargin = viewLocation.right - child.getWidth();
        params.topMargin = viewLocation.top - child.getHeight();
        child.setLayoutParams(params);
    }

    public static Rect getViewLocationRelativeTo(View view,
            View relativeToView) {
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);

        int[] relativeToViewLocation = new int[2];
        relativeToView.getLocationInWindow(relativeToViewLocation);

        int x = viewLocation[0] - relativeToViewLocation[0];
        int y = viewLocation[1] - relativeToViewLocation[1];
        int w = view.getWidth();
        int h = view.getHeight();
        return new Rect(x, y, x + w, y + h);
    }
}

Related Tutorials