get Gravity from View - Android User Interface

Android examples for User Interface:View

Description

get Gravity from View

Demo Code


//package com.java2s;

import android.annotation.TargetApi;

import android.os.Build;
import android.view.Gravity;

import android.view.View;

public class Main {

    public final static int getGravity(View anchor) {
        int windowWidth = anchor.getRootView().getMeasuredWidth();
        return getGravity(anchor, windowWidth * 2 / 5);
    }/* ww  w  .  ja  v  a2  s  . co  m*/

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public final static int getGravity(View anchor, int popupWidth) {
        int gravity = 0;

        int windowHeight = anchor.getRootView().getMeasuredHeight();

        int anchorParentWidth = ((View) anchor.getParent())
                .getMeasuredWidth();
        int anchorWidth = anchor.getMeasuredWidth();
        int anchorHeight = anchor.getMeasuredHeight();
        int anchorLeft = anchor.getLeft();

        // int xPos, yPos;
        int[] location = new int[2];
        anchor.getLocationInWindow(location);
        int anchorX = location[0];
        int anchorY = location[1];

        // anchor
        if (anchorLeft > anchorParentWidth / 2
                && anchorX + anchorWidth > popupWidth) {
            gravity |= Gravity.RIGHT;
        } else {
            gravity |= Gravity.LEFT;
        }

        if (anchorY + anchorHeight > windowHeight / 2) {
            gravity |= Gravity.BOTTOM;
        } else {
            gravity |= Gravity.TOP;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            gravity |= Gravity.RELATIVE_LAYOUT_DIRECTION;
        }

        return gravity;
    }
}

Related Tutorials