Example usage for android.util DisplayMetrics DisplayMetrics

List of usage examples for android.util DisplayMetrics DisplayMetrics

Introduction

In this page you can find the example usage for android.util DisplayMetrics DisplayMetrics.

Prototype

public DisplayMetrics() 

Source Link

Usage

From source file:com.microsoft.windowsazure.mobileservices.LoginManager.java

/**
 * Creates the UI for the interactive authentication process
 * //from  w ww .ja v a 2s .c om
 * @param provider
 *            The provider used for the authentication process
 * @param startUrl
 *            The initial URL for the authentication process
 * @param endUrl
 *            The final URL for the authentication process
 * @param context
 *            The context used to create the authentication dialog
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
private void showLoginUI(final String startUrl, final String endUrl, final Context context,
        LoginUIOperationCallback callback) {
    if (startUrl == null || startUrl == "") {
        throw new IllegalArgumentException("startUrl can not be null or empty");
    }

    if (endUrl == null || endUrl == "") {
        throw new IllegalArgumentException("endUrl can not be null or empty");
    }

    if (context == null) {
        throw new IllegalArgumentException("context can not be null");
    }

    final LoginUIOperationCallback externalCallback = callback;
    final AlertDialog.Builder builder = new AlertDialog.Builder(context);
    // Create the Web View to show the login page
    final WebView wv = new WebView(context);
    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

        @Override
        public void onCancel(DialogInterface dialog) {
            if (externalCallback != null) {
                externalCallback.onCompleted(null, new MobileServiceException("User Canceled"));
            }
        }
    });
    wv.getSettings().setJavaScriptEnabled(true);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int webViewHeight = displaymetrics.heightPixels;

    wv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, webViewHeight));

    wv.requestFocus(View.FOCUS_DOWN);
    wv.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP) {
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
            }

            return false;
        }
    });

    // Create a LinearLayout and add the WebView to the Layout
    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(wv);

    // Add a dummy EditText to the layout as a workaround for a bug
    // that prevents showing the keyboard for the WebView on some devices
    EditText dummyEditText = new EditText(context);
    dummyEditText.setVisibility(View.GONE);
    layout.addView(dummyEditText);

    // Add the layout to the dialog
    builder.setView(layout);

    final AlertDialog dialog = builder.create();

    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // If the URL of the started page matches with the final URL
            // format, the login process finished
            if (isFinalUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(url, null);
                }

                dialog.dismiss();
            }

            super.onPageStarted(view, url, favicon);
        }

        // Checks if the given URL matches with the final URL's format
        private boolean isFinalUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(endUrl);
        }

        // Checks if the given URL matches with the start URL's format
        private boolean isStartUrl(String url) {
            if (url == null) {
                return false;
            }

            return url.startsWith(startUrl);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (isStartUrl(url)) {
                if (externalCallback != null) {
                    externalCallback.onCompleted(null, new MobileServiceException(
                            "Logging in with the selected authentication provider is not enabled"));
                }

                dialog.dismiss();
            }
        }
    });

    wv.loadUrl(startUrl);
    dialog.show();
}

From source file:com.tapcentive.sdk.actions.TapMessageFragment.java

/**
 * Gets the display metrics.//from  w  ww.  jav  a 2s.  c  om
 * 
 * @return the display metrics
 */
private void getDisplayMetrics() {
    // determine the screen size used for the animation
    DisplayMetrics dimension = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(dimension);
    TypedValue tv = new TypedValue();
    getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
    int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
    int statusBarHeight = getResources()
            .getDimensionPixelSize(getResources().getIdentifier("status_bar_height", "dimen", "android"));

    usableHeight = dimension.heightPixels - (actionBarHeight + statusBarHeight);
}

From source file:com.ichi2.anki.Reviewer.java

@SuppressLint("NewApi")
@Override/*from   w w  w. j ava2 s . c  o m*/
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.reviewer, menu);
    Resources res = getResources();
    if (mCurrentCard != null && mCurrentCard.note().hasTag("marked")) {
        menu.findItem(R.id.action_mark_card).setTitle(R.string.menu_unmark_note)
                .setIcon(R.drawable.ic_star_white_24dp);
    } else {
        menu.findItem(R.id.action_mark_card).setTitle(R.string.menu_mark_note)
                .setIcon(R.drawable.ic_star_outline_white_24dp);
    }
    if (colIsOpen() && getCol().undoAvailable()) {
        menu.findItem(R.id.action_undo).setEnabled(true).getIcon().setAlpha(Themes.ALPHA_ICON_ENABLED_LIGHT);
    } else {
        menu.findItem(R.id.action_undo).setEnabled(false).getIcon().setAlpha(Themes.ALPHA_ICON_DISABLED_LIGHT);
    }
    if (mPrefWhiteboard) {
        // Don't force showing mark icon when whiteboard enabled
        // TODO: allow user to customize which icons are force-shown
        MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_mark_card),
                MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
        // Check if we can forceably squeeze in 3 items into the action bar, if not hide "show whiteboard"
        if (CompatHelper.getSdkVersion() >= 14 && !ViewConfiguration.get(this).hasPermanentMenuKey()) {
            // Android 4.x device with overflow menu in the action bar and small screen can't
            // support forcing 2 extra items into the action bar
            Display display = getWindowManager().getDefaultDisplay();
            DisplayMetrics outMetrics = new DisplayMetrics();
            display.getMetrics(outMetrics);
            float density = getResources().getDisplayMetrics().density;
            float dpWidth = outMetrics.widthPixels / density;
            if (dpWidth < 360) {
                menu.findItem(R.id.action_hide_whiteboard).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            }
        }
        // Configure the whiteboard related items in the action bar
        menu.findItem(R.id.action_enable_whiteboard).setTitle(R.string.disable_whiteboard);
        menu.findItem(R.id.action_hide_whiteboard).setVisible(true);
        menu.findItem(R.id.action_clear_whiteboard).setVisible(true);

        Drawable whiteboardIcon = getResources().getDrawable(R.drawable.ic_gesture_white_24dp);
        if (mShowWhiteboard) {
            whiteboardIcon.setAlpha(255);
            menu.findItem(R.id.action_hide_whiteboard).setIcon(whiteboardIcon);
            menu.findItem(R.id.action_hide_whiteboard).setTitle(R.string.hide_whiteboard);
        } else {
            whiteboardIcon.setAlpha(77);
            menu.findItem(R.id.action_hide_whiteboard).setIcon(whiteboardIcon);
            menu.findItem(R.id.action_hide_whiteboard).setTitle(R.string.show_whiteboard);
        }
    } else {
        menu.findItem(R.id.action_enable_whiteboard).setTitle(R.string.enable_whiteboard);
    }
    if (!CompatHelper.isHoneycomb() && !mDisableClipboard) {
        menu.findItem(R.id.action_search_dictionary).setVisible(true)
                .setEnabled(!(mPrefWhiteboard && mShowWhiteboard))
                .setTitle(clipboardHasText() ? Lookup.getSearchStringTitle()
                        : res.getString(R.string.menu_select));
    }
    if (getCol().getDecks().isDyn(getParentDid())) {
        menu.findItem(R.id.action_open_deck_options).setVisible(false);
    }
    return super.onCreateOptionsMenu(menu);
}

From source file:com.yamin.kk.vlc.Util.java

public static int convertPxToDp(int px) {
    WindowManager wm = (WindowManager) VLCApplication.getAppContext().getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);//from   w w w  . j av a  2  s. c  om
    float logicalDensity = metrics.density;
    int dp = Math.round(px / logicalDensity);
    return dp;
}

From source file:com.gizwits.gizdataaccesssdkdemo.activitys.MainActivity.java

/**
 * .// www . j  a  va2s . c om
 * 
 * @return the dialog
 */
public Dialog dateTimePicKDialog() {
    DisplayMetrics dm = new DisplayMetrics();
    dm = this.getResources().getDisplayMetrics();
    int screenWidth = dm.widthPixels;
    int screenHeight = dm.heightPixels;
    LinearLayout dateTimeLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.dialog_time, null);

    etLimit = (EditText) dateTimeLayout.findViewById(R.id.etLimit);
    etSkip = (EditText) dateTimeLayout.findViewById(R.id.etSkip);
    etYearStart = (EditText) dateTimeLayout.findViewById(R.id.etYearStart);
    etYearEnd = (EditText) dateTimeLayout.findViewById(R.id.etYearEnd);
    etMonStart = (EditText) dateTimeLayout.findViewById(R.id.etMonStart);
    etMonEnd = (EditText) dateTimeLayout.findViewById(R.id.etMonEnd);
    etDayStart = (EditText) dateTimeLayout.findViewById(R.id.etDayStart);
    etDayEnd = (EditText) dateTimeLayout.findViewById(R.id.etDayEnd);
    etHourStart = (EditText) dateTimeLayout.findViewById(R.id.etHourStart);
    etHourEnd = (EditText) dateTimeLayout.findViewById(R.id.etHourEnd);
    etMinStart = (EditText) dateTimeLayout.findViewById(R.id.etMinStart);
    etMinEnd = (EditText) dateTimeLayout.findViewById(R.id.etMinEnd);
    etSecStart = (EditText) dateTimeLayout.findViewById(R.id.etSecStart);
    etSecEnd = (EditText) dateTimeLayout.findViewById(R.id.etSecEnd);
    btnStartLoad = (Button) dateTimeLayout.findViewById(R.id.btnStartLoad);
    btnStartLoad.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            loadData();

        }
    });

    dialog = new Dialog(this);
    WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
    params.width = (int) (screenWidth * 0.8);
    params.height = screenHeight / 5;
    params.width = (int) (screenWidth * 0.8);
    params.height = (int) (screenHeight * 0.8);
    dialog.getWindow().setAttributes(params);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setContentView(dateTimeLayout);

    return dialog;
}

From source file:com.eyekabob.ArtistInfo.java

private void handleImageResponse(Bitmap img) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float metWidth = metrics.widthPixels;
    float imgWidth = img.getWidth();
    float ratio = metWidth / imgWidth;
    // Add a little buffer room
    int newWidth = (int) Math.floor(img.getWidth() * ratio) - 50;
    int newHeight = (int) Math.floor(img.getHeight() * ratio) - 50;

    ImageView iv = (ImageView) findViewById(R.id.infoImageView);
    Bitmap rescaledImg = Bitmap.createScaledBitmap(img, newWidth, newHeight, false);
    iv.setImageBitmap(rescaledImg);/*from   w  w w . jav a 2 s  . c  o  m*/
    imageInfoReturned = true;
    dismissDialogIfReady();
}

From source file:com.ezartech.ezar.videooverlay.ezAR.java

private void init(JSONArray args, final CallbackContext callbackContext) {
    this.callbackContext = callbackContext;

    supportSnapshot = getSnapshotPlugin() != null;

    if (args != null) {
        String rgb = DEFAULT_RGB;
        try {//from w  ww .  ja  va2s.co m
            rgb = args.getString(0);
        } catch (JSONException e) {
            //do nothing; resort to DEFAULT_RGB
        }

        setBackgroundColor(Color.parseColor(rgb));
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webViewView.setBackgroundColor(getBackgroundColor());
            }
        });
    }

    if (!PermissionHelper.hasPermission(this, permissions[0])) {
        PermissionHelper.requestPermission(this, CAMERA_SEC, Manifest.permission.CAMERA);
        return;
    }

    JSONObject jsonObject = new JSONObject();
    try {
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics m = new DisplayMetrics();
        display.getMetrics(m);

        jsonObject.put("displayWidth", m.widthPixels);
        jsonObject.put("displayHeight", m.heightPixels);

        int mNumberOfCameras = Camera.getNumberOfCameras();
        Log.d(TAG, "Cameras:" + mNumberOfCameras);

        // Find the ID of the back-facing ("default") camera
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);

            Parameters parameters;
            Camera open = null;
            try {
                open = Camera.open(i);
                parameters = open.getParameters();
            } finally {
                if (open != null) {
                    open.release();
                }
            }

            Log.d(TAG, "Camera facing:" + cameraInfo.facing);

            CameraDirection type = null;
            for (CameraDirection f : CameraDirection.values()) {
                if (f.getDirection() == cameraInfo.facing) {
                    type = f;
                }
            }

            if (type != null) {
                double zoom = 0;
                double maxZoom = 0;
                if (parameters.isZoomSupported()) {
                    maxZoom = (parameters.getMaxZoom() + 1) / 10.0;
                    zoom = Math.min(parameters.getZoom() / 10.0 + 1, maxZoom);
                }

                JSONObject jsonCamera = new JSONObject();
                jsonCamera.put("id", i);
                jsonCamera.put("position", type.toString());
                jsonCamera.put("zoom", zoom);
                jsonCamera.put("maxZoom", maxZoom);
                jsonObject.put(type.toString(), jsonCamera);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Can't set exception", e);
    }

    callbackContext.success(jsonObject);
}

From source file:com.felkertech.n.tv.fragments.LeanbackFragment.java

private void prepareBackgroundManager() {
    try {/*from www. ja va 2 s  .  c o  m*/
        mBackgroundManager = BackgroundManager.getInstance(getActivity());
        mBackgroundManager.attach(getActivity().getWindow());
        mDefaultBackground = getResources().getDrawable(R.drawable.c_background5);
        mBackgroundManager.setDrawable(getResources().getDrawable(R.drawable.c_background5));
        mMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
    } catch (Exception ignored) {
    }
}

From source file:fr.univsavoie.ltp.client.map.Popup.java

public final void popupGetStatus(JSONArray pStatusesArray) {
    DisplayMetrics dm = new DisplayMetrics();
    this.activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

    //final int height = dm.heightPixels;
    final int width = dm.widthPixels;
    final int height = dm.heightPixels;

    int popupWidth = (int) (width * 0.75);
    int popupHeight = height;

    // Inflate the popup_layout.xml
    ScrollView viewGroup = (ScrollView) this.activity.findViewById(R.id.popupGetStatus);
    LayoutInflater layoutInflater = (LayoutInflater) this.activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final View layout = layoutInflater.inflate(R.layout.popup_get_status, viewGroup);
    layout.setBackgroundResource(R.drawable.popup_gradient);

    // Crer le PopupWindow
    final PopupWindow popupPublishStatus = new PopupWindow(layout, popupWidth, LayoutParams.WRAP_CONTENT, true);
    popupPublishStatus.setBackgroundDrawable(new BitmapDrawable());
    popupPublishStatus.setOutsideTouchable(true);

    // Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
    final int OFFSET_X = 0;
    final int OFFSET_Y = 0;

    // Displaying the popup at the specified location, + offsets.
    this.activity.findViewById(R.id.layoutMain).post(new Runnable() {
        public void run() {
            popupPublishStatus.showAtLocation(layout, Gravity.CENTER, OFFSET_X, OFFSET_Y);
        }// w  w w.j a va 2  s. c  om
    });

    /*
     * Evenements composants du PopupWindow
     */

    // Find the ListView resource. 
    ListView mainListView = (ListView) layout.findViewById(R.id.listViewStatus);

    ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

    SimpleAdapter adapter = new SimpleAdapter(this.activity, list, R.layout.custom_row_view,
            new String[] { "content", "lat", "lon" }, new int[] { R.id.text1, R.id.text2, R.id.text3 });

    try {
        // Appel REST pour recuperer les status de l'utilisateur connect
        //Session session = new Session(this.activity);
        //session.parseJSONUrl("https://jibiki.univ-savoie.fr/ltpdev/rest.php/api/1/statuses", "STATUSES", "GET");

        // Parser la liste des amis dans le OverlayItem ArrayList
        HashMap<String, String> temp;
        for (int i = 0; (i < 6); i++) {
            // Obtenir le status
            JSONObject status = pStatusesArray.getJSONObject(i);

            temp = new HashMap<String, String>();
            temp.put("content", status.getString("content"));
            temp.put("lat", String.valueOf(status.getDouble("lat")));
            temp.put("lon", String.valueOf(status.getDouble("lon")));
            list.add(temp);
        }
    } catch (JSONException jex) {
        Log.e("Catch", "popupGetStatus / JSONException : " + jex.getStackTrace());
    } catch (Exception ex) {
        Log.e("Catch", "popupGetStatus / Exception : " + ex.getLocalizedMessage());
    }

    mainListView.setAdapter(adapter);
}

From source file:com.appassit.common.Utils.java

public static float sp2px(Context context, float sp) {
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics displaymetrics = new DisplayMetrics();
    display.getMetrics(displaymetrics);//from www . ja  v a 2s .co m

    final float scale = displaymetrics.scaledDensity;
    return sp * scale;
}