Example usage for android.content.res Resources getDisplayMetrics

List of usage examples for android.content.res Resources getDisplayMetrics

Introduction

In this page you can find the example usage for android.content.res Resources getDisplayMetrics.

Prototype

public DisplayMetrics getDisplayMetrics() 

Source Link

Document

Return the current display metrics that are in effect for this resource object.

Usage

From source file:com.android.contacts.common.list.ShortcutIntentBuilder.java

/**
 * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
 * number, and if there is a photo also adds the call action icon.
 *//*w ww .java  2  s  .c om*/
private Bitmap generatePhoneNumberIcon(Drawable photo, int phoneType, String phoneLabel, int actionResId) {
    final Resources r = mContext.getResources();
    final float density = r.getDisplayMetrics().density;

    Bitmap phoneIcon = ((BitmapDrawable) r.getDrawableForDensity(actionResId, mIconDensity)).getBitmap();

    Bitmap icon = generateQuickContactIcon(photo);
    Canvas canvas = new Canvas(icon);

    // Copy in the photo
    Paint photoPaint = new Paint();
    photoPaint.setDither(true);
    photoPaint.setFilterBitmap(true);
    Rect dst = new Rect(0, 0, mIconSize, mIconSize);

    // Create an overlay for the phone number type
    CharSequence overlay = Phone.getTypeLabel(r, phoneType, phoneLabel);

    if (overlay != null) {
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        textPaint.setTextSize(r.getDimension(R.dimen.shortcut_overlay_text_size));
        textPaint.setColor(r.getColor(R.color.textColorIconOverlay));
        textPaint.setShadowLayer(4f, 0, 2f, r.getColor(R.color.textColorIconOverlayShadow));

        final FontMetricsInt fmi = textPaint.getFontMetricsInt();

        // First fill in a darker background around the text to be drawn
        final Paint workPaint = new Paint();
        workPaint.setColor(mOverlayTextBackgroundColor);
        workPaint.setStyle(Paint.Style.FILL);
        final int textPadding = r.getDimensionPixelOffset(R.dimen.shortcut_overlay_text_background_padding);
        final int textBandHeight = (fmi.descent - fmi.ascent) + textPadding * 2;
        dst.set(0, mIconSize - textBandHeight, mIconSize, mIconSize);
        canvas.drawRect(dst, workPaint);

        overlay = TextUtils.ellipsize(overlay, textPaint, mIconSize, TruncateAt.END);
        final float textWidth = textPaint.measureText(overlay, 0, overlay.length());
        canvas.drawText(overlay, 0, overlay.length(), (mIconSize - textWidth) / 2,
                mIconSize - fmi.descent - textPadding, textPaint);
    }

    // Draw the phone action icon as an overlay
    Rect src = new Rect(0, 0, phoneIcon.getWidth(), phoneIcon.getHeight());
    int iconWidth = icon.getWidth();
    dst.set(iconWidth - ((int) (20 * density)), -1, iconWidth, ((int) (19 * density)));
    canvas.drawBitmap(phoneIcon, src, dst, photoPaint);

    canvas.setBitmap(null);

    return icon;
}

From source file:br.com.frs.foodrestrictions.MessageVegan.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_message_vegan, container, false);

    String language = getArguments().getString(MessageLanguageSelector.ARG_LANGUAGE);

    TextView tv = (TextView) v.findViewById(R.id.tvVegegan);

    /* //TODO - Find a better way of doing it
     * I don't believe that this is the best approach to handle this problem but it is
     * the only way I found to do it so far. Do you have any better idea?
     * please help me here :D/*from w w w . j  ava  2  s.  co  m*/
     */

    /* Getting the current resource  and config info */
    Resources rsc = v.getContext().getResources();
    Configuration config = rsc.getConfiguration();
    /* Saving the original locale before changing to the new one
     * just to show the texts
     */
    Locale orgLocale = config.locale;

    if (language != null) {
        config.locale = new Locale(language);
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    /* Updating the layout with the new selected language */
    tv.setText(rsc.getString(R.string.msg_vegan));

    /* Return to last locale to keep the app as it was before */
    config.locale = orgLocale;
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());

    return v;
}

From source file:br.com.frs.foodrestrictions.MessageVegetarian.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.activity_message_vegetarian, container, false);

    String language = getArguments().getString(MessageLanguageSelector.ARG_LANGUAGE);

    TextView tv = (TextView) v.findViewById(R.id.tvVegetarian);

    /* //TODO - Find a better way of doing it
     * I don't believe that this is the best approach to handle this problem but it is
     * the only way I found to do it so far. Do you have any better idea?
     * please help me here :D/*from  ww w .j a  va2 s.com*/
     */

    /* Getting the current resource  and config info */
    Resources rsc = v.getContext().getResources();
    Configuration config = rsc.getConfiguration();
    /* Saving the original locale before changing to the new one
     * just to show the texts
     */
    Locale orgLocale = config.locale;

    if (language != null) {
        config.locale = new Locale(language);
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    /* Updating the layout with the new selected language */
    tv.setText(rsc.getString(R.string.msg_veget));

    /* Return to last locale to keep the app as it was before */
    config.locale = orgLocale;
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());

    return v;
}

From source file:org.openmrs.mobile.activities.formdisplay.FormDisplayPageFragment.java

private LinearLayout.LayoutParams getAndAdjustLinearLayoutParams(LinearLayout linearLayout) {
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

    linearLayout.setOrientation(LinearLayout.VERTICAL);

    Resources r = getActivity().getResources();
    float pxLeftMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());
    float pxTopMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());
    float pxRightMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());
    float pxBottomMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());
    layoutParams.setMargins(Math.round(pxLeftMargin), Math.round(pxTopMargin), Math.round(pxRightMargin),
            Math.round(pxBottomMargin));

    return layoutParams;
}

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
* Converts dp's to pixels in relation to the users' screen
* @param dp/*from  w  w w  .  ja  v a 2 s  . c  o m*/
* @param context
* @return
*/
private int convertDpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    int px = (int) (dp * (metrics.densityDpi / 160f));
    return px;
}

From source file:de.luhmer.owncloudnewsreader.NewsReaderListFragment.java

public void bindUserInfoToUI(boolean testMode) {
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String mUsername = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null);
    String mOc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING,
            getString(R.string.app_name));

    userTextView.setText(mUsername);//  w  ww.j a v a  2 s.  co  m
    urlTextView.setText(mOc_root_path);

    if (testMode) { //Hide real url in test mode
        urlTextView.setText("https://example.com/owncloud");
    }

    String uInfo = mPrefs.getString("USER_INFO", null);
    if (uInfo == null)
        return;

    try {
        UserInfo userInfo = (UserInfo) fromString(uInfo);
        if (userInfo.mDisplayName != null)
            userTextView.setText(userInfo.mDisplayName);

        if (userInfo.mAvatar != null) {
            Resources r = getResources();
            float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, r.getDisplayMetrics());
            RoundedBitmapDisplayer.RoundedDrawable roundedAvatar = new RoundedBitmapDisplayer.RoundedDrawable(
                    userInfo.mAvatar, (int) px, 0);
            headerLogo.setImageDrawable(roundedAvatar);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.quarterfull.newsAndroid.NewsReaderListFragment.java

public void bindUserInfoToUI(boolean testMode) {
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    String mUsername = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null);
    String mOc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING,
            getString(R.string.app_name));
    mOc_root_path = mOc_root_path.replace("http://", "").replace("https://", ""); //Remove http:// or https://

    userTextView.setText(mUsername);/* ww w.j a v a  2 s .c  o m*/
    urlTextView.setText(mOc_root_path);

    if (testMode) { //Hide real url in test mode
        urlTextView.setText("example.com/ownCloud");
    }

    String uInfo = mPrefs.getString("USER_INFO", null);
    if (uInfo == null)
        return;

    try {
        UserInfo userInfo = (UserInfo) fromString(uInfo);
        if (userInfo.mDisplayName != null)
            userTextView.setText(userInfo.mDisplayName);

        if (userInfo.mAvatar != null) {
            Resources r = getResources();
            float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, r.getDisplayMetrics());
            RoundedBitmapDisplayer.RoundedDrawable roundedAvatar = new RoundedBitmapDisplayer.RoundedDrawable(
                    userInfo.mAvatar, (int) px, 0);
            headerLogo.setImageDrawable(roundedAvatar);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.github.segoh.viewpagerindicator.ViewPagerIndicator.java

public ViewPagerIndicator(final Context context, final AttributeSet attrs, final int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    if (isInEditMode()) {
        return;//from   www  .j  a va  2s  .  c  om
    }
    final Resources res = getResources();
    final int defaultCurrentPageColor = res.getColor(R.color.vpi__current_page);
    final int defaultPageColor = res.getColor(R.color.vpi__page);
    final float defaultRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            res.getDisplayMetrics());
    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator, defStyleAttr, 0);
    if (a != null) {
        mPaintPage.setStyle(Paint.Style.FILL);
        mPaintPage.setColor(a.getColor(R.styleable.ViewPagerIndicator_pageColor, defaultPageColor));
        mPaintCurrentPage.setStyle(Paint.Style.FILL);
        mPaintCurrentPage
                .setColor(a.getColor(R.styleable.ViewPagerIndicator_currentPageColor, defaultCurrentPageColor));
        mRadius = a.getDimension(R.styleable.ViewPagerIndicator_radius, defaultRadius);
        Drawable background = a.getDrawable(R.styleable.ViewPagerIndicator_android_background);
        setBackgroundDrawable(background);
        a.recycle();
    }
}

From source file:com.actionbarsherlock.internal.view.menu.ActionMenuPresenter.java

@Override
public void initForMenu(Context context, MenuBuilder menu) {
    super.initForMenu(context, menu);

    final Resources res = context.getResources();

    if (!mWidthLimitSet) {
        mWidthLimit = res.getDisplayMetrics().widthPixels / 2;
    }//  www .  j a  v  a2 s  . c  o  m

    // Measure for initial configuration
    if (!mMaxItemsSet) {
        mMaxItems = res.getInteger(R.integer.abs__max_action_buttons);
    }

    mActionItemWidthLimit = mWidthLimit;

    mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density);

    // Drop a scrap view as it may no longer reflect the proper context/config.
    mScrapActionButtonView = null;
}

From source file:ota.otaupdates.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (sharedPreferences.getBoolean("force_english", false)) {
        Locale myLocale = new Locale("en");
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;/*from ww  w . j a v a  2s.co  m*/
        res.updateConfiguration(conf, dm);
    }

    if (sharedPreferences.getBoolean("apptheme_light", false))
        setTheme(R.style.AppTheme_Light);
    else
        setTheme(R.style.AppTheme_Dark);

    setContentView(R.layout.activity_main);

    build_url
            .append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
                    : getString(R.string.download_url))
            .append("/api/").append(Build.DEVICE).append("/").append(Build.TIME / 1000);

    build_dl_url.append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url)).append("/builds/");

    delta_url.append((Utils.doesPropExist(Constants.URL_PROP) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url))).append("/delta/").append(Build.VERSION.INCREMENTAL);

    delta_dl_url.append((Utils.doesPropExist(Constants.URL_PROP)) ? Utils.getProp(Constants.URL_PROP)
            : getString(R.string.download_url)).append("/deltas/");

    otaList = new ArrayList<>();
    get_builds();
    pb = (ProgressBar) findViewById(R.id.pb);
    pb.setVisibility(View.VISIBLE);

    final ListView ota_list = (ListView) findViewById(R.id.ota_list);

    adapter = new OTAUpdatesAdapter(getApplicationContext(), R.layout.row, otaList);
    ota_list.setAdapter(adapter);

    final CoordinatorLayout coordinator_root = (CoordinatorLayout) findViewById(R.id.coordinator_root);
    ota_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long id) {
            final String url = build_dl_url.toString() + otaList.get(position).getOta_filename();

            if (Build.VERSION.SDK_INT >= 23 && !checkPermission())
                allow_write_sd();
            else if (sharedPreferences.getBoolean("disable_mobile", true) && isMobileDataEnabled()) {
                sb_network = Snackbar.make(coordinator_root, getString(R.string.disable_mobile_message),
                        Snackbar.LENGTH_SHORT);
                sb_network.getView()
                        .setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorSecond));
                sb_network.show();
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        create_notification(1, getString(R.string.app_name), getString(
                                R.string.downloader_notification, otaList.get(position).getOta_filename()));
                        Utils.DownloadFromUrl(url, otaList.get(position).getOta_filename());
                        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (MD5.checkMD5(otaList.get(position).getOta_md5(),
                                        new File(DL_PATH + otaList.get(position).getOta_filename()))
                                        || !sharedPreferences.getBoolean("md5_checking", true))
                                    trigger_autoinstall(DL_PATH + otaList.get(position).getOta_filename());
                                else {
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle(getString(R.string.md5_title))
                                            .setMessage(getString(R.string.md5_message)).setNeutralButton(
                                                    R.string.button_ok, new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                        }
                                                    })
                                            .show();
                                }
                            }
                        });
                    }
                }).start();
            }
        }
    });

}