Example usage for android.view Display getMetrics

List of usage examples for android.view Display getMetrics

Introduction

In this page you can find the example usage for android.view Display getMetrics.

Prototype

public void getMetrics(DisplayMetrics outMetrics) 

Source Link

Document

Gets display metrics that describe the size and density of this display.

Usage

From source file:com.shopify.buy.ui.ProductDetailsFragmentView.java

/**
 * Sets up the image area.//w w w. j a v  a2  s .c  o m
 * If the product has images, the height of the image area will be set equal to the width of the screen.
 * If the product does not have an image, the height of the image area will be equal to the action bar height.
 */
private void initializeImageArea() {
    imageAreaWrapper = (ViewGroup) findViewById(R.id.product_details_image_wrapper);

    WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
    Display display = windowManager.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);

    int screenWidth = metrics.widthPixels;
    int screenHeight = metrics.heightPixels;

    if (DeviceUtils.isTablet(getResources())) {
        screenHeight = fragment.getActivity().getWindow().getAttributes().height;
        screenWidth = fragment.getActivity().getWindow().getAttributes().width;
    }

    // Make sure the description area below the image is at least 40% of the screen height
    int minDetailsHeightInPx = Math.round(screenHeight * 0.4f);

    boolean hasImage = product != null && product.hasImage();
    int maxHeightInPx = hasImage ? screenHeight - minDetailsHeightInPx : getActionBarHeightPixels();
    imageAreaHeight = Math.min(screenWidth, maxHeightInPx);

    // Create the image pager, and set the listener
    imagePager = (ViewPager) findViewById(R.id.image_pager);
    imagePager.setAdapter(new ProductImagePagerAdapter(null, screenWidth, imageAreaHeight, this, 0));
    imagePager.setOnPageChangeListener(this);

    // Set the touch handler that registers flinging down/up for resizing image
    imageAreaTouchHandler = new ProductDetailsImageAreaTouchHandler(getContext(), this);
    imagePager.setOnTouchListener(imageAreaTouchHandler);

    pagingIndicator = (TabLayout) findViewById(R.id.indicator);

    ViewGroup.LayoutParams params = imageAreaWrapper.getLayoutParams();
    params.height = imageAreaHeight;
}

From source file:com.example.ray.firstapp.bottombar.BottomBar.java

private static void navBarMagic(Activity activity, final BottomBar bottomBar) {
    Resources res = activity.getResources();
    int softMenuIdentifier = res.getIdentifier("config_showNavigationBar", "bool", "android");
    int navBarIdentifier = res.getIdentifier("navigation_bar_height", "dimen", "android");
    int navBarHeight = 0;

    if (navBarIdentifier > 0) {
        navBarHeight = res.getDimensionPixelSize(navBarIdentifier);
    }/*from   w  w w  .j  av  a2s .  co m*/

    if (!bottomBar.drawBehindNavBar() || navBarHeight == 0
            || (!(softMenuIdentifier > 0 && res.getBoolean(softMenuIdentifier)))) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
            && ViewConfiguration.get(activity).hasPermanentMenuKey()) {
        return;
    }

    /**
     * Copy-paste coding made possible by:
     * http://stackoverflow.com/a/14871974/940036
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Display d = activity.getWindowManager().getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        d.getRealMetrics(realDisplayMetrics);

        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);

        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;

        boolean hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;

        if (!hasSoftwareKeys) {
            return;
        }
    }
    /**
     * End of delicious copy-paste code
     */

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        activity.getWindow().getAttributes().flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;

        if (bottomBar.useTopOffset()) {
            int offset;
            int statusBarResource = res.getIdentifier("status_bar_height", "dimen", "android");

            if (statusBarResource > 0) {
                offset = res.getDimensionPixelSize(statusBarResource);
            } else {
                offset = MiscUtils.dpToPixel(activity, 25);
            }

            if (!bottomBar.useOnlyStatusbarOffset()) {
                TypedValue tv = new TypedValue();
                if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    offset += TypedValue.complexToDimensionPixelSize(tv.data, res.getDisplayMetrics());
                } else {
                    offset += MiscUtils.dpToPixel(activity, 56);
                }
            }

            bottomBar.getUserContainer().setPadding(0, offset, 0, 0);
        }

        final View outerContainer = bottomBar.getOuterContainer();
        final int navBarHeightCopy = navBarHeight;
        bottomBar.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        bottomBar.shyHeightAlreadyCalculated();

                        int newHeight = outerContainer.getHeight() + navBarHeightCopy;
                        outerContainer.getLayoutParams().height = newHeight;

                        if (bottomBar.isShy()) {
                            int defaultOffset = bottomBar.useExtraOffset() ? navBarHeightCopy : 0;
                            bottomBar.setTranslationY(defaultOffset);
                            ((CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams())
                                    .setBehavior(new BottomNavigationBehavior(newHeight, defaultOffset));
                        }

                        ViewTreeObserver obs = outerContainer.getViewTreeObserver();

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            obs.removeOnGlobalLayoutListener(this);
                        } else {
                            obs.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    }
}

From source file:com.tomer.alwayson.SettingsFragment.java

private boolean hasSoftKeys() {
    boolean hasSoftwareKeys;

    Display d = getActivity().getWindowManager().getDefaultDisplay();

    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
    d.getRealMetrics(realDisplayMetrics);

    int realHeight = realDisplayMetrics.heightPixels;
    int realWidth = realDisplayMetrics.widthPixels;

    DisplayMetrics displayMetrics = new DisplayMetrics();
    d.getMetrics(displayMetrics);

    int displayHeight = displayMetrics.heightPixels;
    int displayWidth = displayMetrics.widthPixels;

    hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;

    prefs.setBool(Prefs.KEYS.HAS_SOFT_KEYS.toString(), hasSoftwareKeys);

    return hasSoftwareKeys;
}

From source file:com.harlan.jxust.ui.view.bottombar.BottomBar.java

private static void navBarMagic(Activity activity, final BottomBar bottomBar) {
    Resources res = activity.getResources();
    int softMenuIdentifier = res.getIdentifier("config_showNavigationBar", "bool", "android");
    int navBarIdentifier = res.getIdentifier("navigation_bar_height", "dimen", "android");
    int navBarHeight = 0;

    if (navBarIdentifier > 0) {
        navBarHeight = res.getDimensionPixelSize(navBarIdentifier);
    }//  w w w  .  ja  v a  2  s  .c  o  m

    if (!bottomBar.drawBehindNavBar() || navBarHeight == 0
            || (!(softMenuIdentifier > 0 && res.getBoolean(softMenuIdentifier)))) {
        return;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
            && ViewConfiguration.get(activity).hasPermanentMenuKey()) {
        return;
    }

    /**
     * Copy-paste coding made possible by:
     * http://stackoverflow.com/a/14871974/940036
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Display d = activity.getWindowManager().getDefaultDisplay();

        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        d.getRealMetrics(realDisplayMetrics);

        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;

        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);

        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;

        boolean hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;

        if (!hasSoftwareKeys) {
            return;
        }
    }
    /**
     * End of delicious copy-paste code
     */

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        activity.getWindow().getAttributes().flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;

        if (bottomBar.useTopOffset()) {
            int offset;
            int statusBarResource = res.getIdentifier("status_bar_height", "dimen", "android");

            if (statusBarResource > 0) {
                offset = res.getDimensionPixelSize(statusBarResource);
            } else {
                offset = MiscUtils.dpToPixel(activity, 25);
            }

            if (!bottomBar.useOnlyStatusbarOffset()) {
                TypedValue tv = new TypedValue();
                if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    offset += TypedValue.complexToDimensionPixelSize(tv.data, res.getDisplayMetrics());
                } else {
                    offset += MiscUtils.dpToPixel(activity, 56);
                }
            }

            bottomBar.getUserContainer().setPadding(0, offset, 0, 0);
        }

        final View outerContainer = bottomBar.getOuterContainer();
        final int navBarHeightCopy = navBarHeight;
        bottomBar.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @SuppressWarnings("deprecation")
                    @Override
                    public void onGlobalLayout() {
                        bottomBar.shyHeightAlreadyCalculated();

                        int newHeight = outerContainer.getHeight() + navBarHeightCopy;
                        outerContainer.getLayoutParams().height = newHeight;

                        if (bottomBar.isShy()) {
                            int defaultOffset = bottomBar.useExtraOffset() ? navBarHeightCopy : 0;
                            bottomBar.setTranslationY(defaultOffset);
                            ((CoordinatorLayout.LayoutParams) bottomBar.getLayoutParams())
                                    .setBehavior(new BottomNavigationBehavior(newHeight, defaultOffset,
                                            bottomBar.isShy(), bottomBar.mIsTabletMode));
                        }

                        ViewTreeObserver obs = outerContainer.getViewTreeObserver();

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            obs.removeOnGlobalLayoutListener(this);
                        } else {
                            obs.removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    }
}

From source file:dev.ronlemire.commoncontrols.MainActivity.java

private boolean isTablet() {
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics displayMetrics = new DisplayMetrics();
    display.getMetrics(displayMetrics);

    int width = displayMetrics.widthPixels / displayMetrics.densityDpi;
    int height = displayMetrics.heightPixels / displayMetrics.densityDpi;

    double screenDiagonal = Math.sqrt(width * width + height * height);
    return (screenDiagonal >= 8.5);
}

From source file:com.undatech.opaque.RemoteCanvas.java

public RemoteCanvas(final Context context, AttributeSet attrSet) {
    super(context, attrSet);
    clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
    final Display display = ((Activity) context).getWindow().getWindowManager().getDefaultDisplay();
    displayWidth = display.getWidth();/*from   w w w .  j  a  v  a 2s.c  om*/
    displayHeight = display.getHeight();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    displayDensity = metrics.density;

    canvasZoomer = new CanvasZoomer(this);
    setScaleType(ImageView.ScaleType.MATRIX);

    if (android.os.Build.MODEL.contains("BlackBerry") || android.os.Build.BRAND.contains("BlackBerry")
            || android.os.Build.MANUFACTURER.contains("BlackBerry")) {
        bb = true;
    }
}

From source file:dev.ronlemire.commoncontrols.MainActivity.java

 private boolean isTablet() {
   Display display = getWindowManager().getDefaultDisplay();
   DisplayMetrics displayMetrics = new DisplayMetrics();
   display.getMetrics(displayMetrics);

   int width = displayMetrics.widthPixels / displayMetrics.densityDpi;
   int height = displayMetrics.heightPixels / displayMetrics.densityDpi;

   double screenDiagonal = Math.sqrt(width * width + height * height);
   return (screenDiagonal >= 8.5);
}

From source file:org.mortbay.ijetty.IJetty.java

License:asdf

public String getDisplayScreenSize() {
    WindowManager w = getWindowManager();
    Display d = w.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    d.getMetrics(metrics);
    // since SDK_INT = 1;
    int widthPixels = metrics.widthPixels;
    int heightPixels = metrics.heightPixels;
    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
        try {// w  ww. j  av  a  2 s.c  om
            widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
            heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
        } catch (Exception ignored) {
            Log.e("-->smallstar", "getDisplayScreenSize error");
        }
    // includes window decorations (statusbar bar/menu bar)
    if (Build.VERSION.SDK_INT >= 17)
        try {
            Point realSize = new Point();
            Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
            widthPixels = realSize.x;
            heightPixels = realSize.y;
        } catch (Exception ignored) {
            Log.e("-->smallstar", "getDisplayScreenSize error");
        }
    return String.valueOf(widthPixels) + "*" + String.valueOf(heightPixels);
}

From source file:ti.modules.titanium.ui.widget.collectionview.TiCollectionView.java

public static Point getScreenDimensions(Context context) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    DisplayMetrics dm = new DisplayMetrics();
    display.getMetrics(dm);

    Point point = new Point();
    point.set(dm.widthPixels, dm.heightPixels);
    return point;
}

From source file:org.navitproject.navit.Navit.java

/** Called when the activity is first created. */
@Override//www . j av a 2  s  .c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    else
        this.getActionBar().hide();

    dialogs = new NavitDialogs(this);

    NavitResources = getResources();

    // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.)
    Navit.startup_intent = this.getIntent();
    // hack! Remember time stamps, and only allow 4 secs. later in onResume to set target!
    Navit.startup_intent_timestamp = System.currentTimeMillis();
    Log.e("Navit", "**1**A " + startup_intent.getAction());
    Log.e("Navit", "**1**D " + startup_intent.getDataString());

    // init translated text
    NavitTextTranslations.init();

    // NOTIFICATION
    // Setup the status bar notification      
    // This notification is removed in the exit() function
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Grab a handle to the NotificationManager
    Notification NavitNotification = new Notification(R.drawable.ic_notify,
            getString(R.string.notification_ticker), System.currentTimeMillis()); // Create a new notification, with the text string to show when the notification first appears
    PendingIntent appIntent = PendingIntent.getActivity(getApplicationContext(), 0, getIntent(), 0);
    //      FIXME : needs a fix for sdk 23
    //      NavitNotification.setLatestEventInfo(getApplicationContext(), "Navit", getString(R.string.notification_event_default), appIntent);   // Set the text in the notification
    //      NavitNotification.flags|=Notification.FLAG_ONGOING_EVENT;   // Ensure that the notification appears in Ongoing
    //      nm.notify(R.string.app_name, NavitNotification);   // Set the notification

    // Status and navigation bar sizes
    // These are platform defaults and do not change with rotation, but we have to figure out which ones apply
    // (is the navigation bar visible? on the side or at the bottom?)
    Resources resources = getResources();
    int shid = resources.getIdentifier("status_bar_height", "dimen", "android");
    int adhid = resources.getIdentifier("action_bar_default_height", "dimen", "android");
    int nhid = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    int nhlid = resources.getIdentifier("navigation_bar_height_landscape", "dimen", "android");
    int nwid = resources.getIdentifier("navigation_bar_width", "dimen", "android");
    status_bar_height = (shid > 0) ? resources.getDimensionPixelSize(shid) : 0;
    action_bar_default_height = (adhid > 0) ? resources.getDimensionPixelSize(adhid) : 0;
    navigation_bar_height = (nhid > 0) ? resources.getDimensionPixelSize(nhid) : 0;
    navigation_bar_height_landscape = (nhlid > 0) ? resources.getDimensionPixelSize(nhlid) : 0;
    navigation_bar_width = (nwid > 0) ? resources.getDimensionPixelSize(nwid) : 0;
    Log.d(TAG, String.format(
            "status_bar_height=%d, action_bar_default_height=%d, navigation_bar_height=%d, navigation_bar_height_landscape=%d, navigation_bar_width=%d",
            status_bar_height, action_bar_default_height, navigation_bar_height,
            navigation_bar_height_landscape, navigation_bar_width));
    if ((ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            || (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
        Log.d(TAG, "ask for permission(s)");
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSIONS_REQUEST_ALL);
    }
    // get the local language -------------
    Locale locale = java.util.Locale.getDefault();
    String lang = locale.getLanguage();
    String langu = lang;
    String langc = lang;
    Log.e("Navit", "lang=" + lang);
    int pos = langu.indexOf('_');
    if (pos != -1) {
        langc = langu.substring(0, pos);
        NavitLanguage = langc + langu.substring(pos).toUpperCase(locale);
        Log.e("Navit", "substring lang " + NavitLanguage.substring(pos).toUpperCase(locale));
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = NavitLanguage.substring(pos).toUpperCase(locale);
    } else {
        String country = locale.getCountry();
        Log.e("Navit", "Country1 " + country);
        Log.e("Navit", "Country2 " + country.toUpperCase(locale));
        NavitLanguage = langc + "_" + country.toUpperCase(locale);
        // set lang. for translation
        NavitTextTranslations.main_language = langc;
        NavitTextTranslations.sub_language = country.toUpperCase(locale);
    }
    Log.e("Navit", "Language " + lang);

    SharedPreferences prefs = getSharedPreferences(NAVIT_PREFS, MODE_PRIVATE);
    map_filename_path = prefs.getString("filenamePath",
            Environment.getExternalStorageDirectory().getPath() + "/navit/");

    // make sure the new path for the navitmap.bin file(s) exist!!
    File navit_maps_dir = new File(map_filename_path);
    navit_maps_dir.mkdirs();

    // make sure the share dir exists
    File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR);
    navit_data_share_dir.mkdirs();

    Display display_ = getWindowManager().getDefaultDisplay();
    int width_ = display_.getWidth();
    int height_ = display_.getHeight();
    metrics = new DisplayMetrics();
    display_.getMetrics(Navit.metrics);
    int densityDpi = (int) ((Navit.metrics.density * 160) - .5f);
    Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_);
    Log.e("Navit", "Navit -> dpi=" + densityDpi);
    Log.e("Navit", "Navit -> density=" + Navit.metrics.density);
    Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity);

    ActivityResults = new NavitActivityResult[16];
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen");

    if (!extractRes(langc, NAVIT_DATA_DIR + "/locale/" + langc + "/LC_MESSAGES/navit.mo")) {
        Log.e("Navit", "Failed to extract language resource " + langc);
    }

    if (densityDpi <= 120) {
        my_display_density = "ldpi";
    } else if (densityDpi <= 160) {
        my_display_density = "mdpi";
    } else if (densityDpi < 240) {
        my_display_density = "hdpi";
    } else if (densityDpi < 320) {
        my_display_density = "xhdpi";
    } else if (densityDpi < 480) {
        my_display_density = "xxhdpi";
    } else if (densityDpi < 640) {
        my_display_density = "xxxhdpi";
    } else {
        Log.e("Navit", "found device of very high density (" + densityDpi + ")");
        Log.e("Navit", "using xxxhdpi values");
        my_display_density = "xxxhdpi";
    }

    if (!extractRes("navit" + my_display_density, NAVIT_DATA_DIR + "/share/navit.xml")) {
        Log.e("Navit", "Failed to extract navit.xml for " + my_display_density);
    }

    // --> dont use android.os.Build.VERSION.SDK_INT, needs API >= 4
    Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK));
    NavitMain(this, NavitLanguage, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density,
            NAVIT_DATA_DIR + "/bin/navit", map_filename_path);

    showInfos();

    Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
}