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.miz.functions.MizLib.java

public static int convertDpToPixels(Context c, int dp) {
    Resources r = c.getResources();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}

From source file:com.miz.functions.MizLib.java

public static int getLargeNotificationWidth(Context c) {
    Resources r = c.getResources();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 360, r.getDisplayMetrics());
}

From source file:dev.ukanth.ufirewall.Api.java

public static void updateLanguage(Context context, String lang) {
    if (!"".equals(lang)) {
        Locale locale = new Locale(lang);
        Resources res = context.getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = locale;/*from  w  ww.  j  a  va2s .  c  om*/
        res.updateConfiguration(conf, dm);
    }
}

From source file:com.android.gallery3d.filtershow.FilterShowActivity.java

public float getPixelsFromDip(float value) {
    Resources r = getResources();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, r.getDisplayMetrics());
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.fragment.MessageCenterFragment.java

private int calculateFabPadding(Context context) {
    Resources res = context.getResources();
    float scale = res.getDisplayMetrics().density;
    return (int) (res.getDimension(R.dimen.apptentive_message_center_bottom_padding) * scale + 0.5f);

}

From source file:org.de.jmg.learn.SettingsActivity.java

private void resize(float scale) {
    //if (scale == 0 && mScale!=1) return;
    Resources resources = _main.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    @SuppressWarnings("unused")
    int Density = metrics.densityDpi;
    try {/*from   w ww.  j a  va2 s  .  co m*/
        int width = mainView.getWidth();
        if (width > 500) {
            width -= lib.dpToPx(40);
        } else {
            width -= lib.dpToPx(40);
        }
        if (scale == 0) {
            mainView.setVisibility(View.INVISIBLE);
            libLearn.gStatus = "Calculating Scale";

            float scale1 = width / (float) (_main.isSmallDevice ? 0
                    : (findViewById(R.id.txtCharsetASCII)).getWidth() + spnASCII.getWidth() + width / 30);
            float scale2 = width / (float) (_main.isSmallDevice ? 0
                    : (findViewById(R.id.txtSounds)).getWidth() + spnSounds.getWidth() + width / 30);
            float scale3 = width / (float) (_main.isSmallDevice ? 0
                    : (findViewById(R.id.txtCharsetASCII)).getWidth() + spnASCII.getWidth() + width / 30);
            scale = (scale1 < scale2) ? scale1 : scale2;
            scale = (scale3 < scale) ? scale3 : scale;
        }
        mScale = scale;

        ViewGroup Settings = (ViewGroup) findViewById(R.id.layoutSettings);
        libLearn.gStatus = "Enumerating ChildViews";
        int ChildCount = Settings.getChildCount();
        for (int i = 0; i < ChildCount; i++) {
            if (i > 100)
                break;
            libLearn.gStatus = "getting view " + i;
            View V = Settings.getChildAt(i);
            /*
            CharSequence cs = V.getContentDescription();
            if (cs != null && cs.length()>0 )
            {
               V.setOnLongClickListener(ViewOnLongClickCD);
            }
            */
            RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) V
                    .getLayoutParams();

            params.topMargin = (int) (params.topMargin * scale);
            params.bottomMargin = (int) (params.bottomMargin * scale);

            if (params.height > 0)
                params.height = (int) (params.height * scale);
            if (V instanceof CheckBox) {
                if (params.width > 0)
                    params.width = ((width - lib.dpToPx(10)) / 3);
            } else {
                if (params.width > 0)
                    params.width = (int) (params.width * scale);
            }
            /*
            if (V == spnSounds) {
               int soundsHeight = spnSounds.getHeight();
               float margin = (float) ((soundsHeight * scale) / 5.25);
               params.topMargin = params.topMargin + (int) margin;
            }
            */
            libLearn.gStatus = "Setting Layoutparams";
            V.setLayoutParams(params);
            // }
            if (V instanceof TextView && !(V instanceof CheckBox)) {
                libLearn.gStatus = "TextView set size";
                TextView t = (TextView) V;
                t.setTextSize(TypedValue.COMPLEX_UNIT_PX, t.getTextSize() * scale);
            } else if (V instanceof Spinner) {
                Spinner spn = (Spinner) V;
                SpinnerAdapter A = spn.getAdapter();
                if (A instanceof AbstractScaledArrayAdapter<?>) {
                    libLearn.gStatus = "Scaling Adapter";
                    AbstractScaledArrayAdapter<?> AA = (AbstractScaledArrayAdapter<?>) A;
                    AA.Scale = AA.Scale * scale;
                    if (spn.getSelectedItemPosition() > -1) {
                        AA.notifyDataSetChanged();
                    }

                }
            } else if (V instanceof CheckBox) {
                libLearn.gStatus = "CheckBox";
                CheckBox c = (CheckBox) V;
                //c.setScaleX(scale);
                //c.setScaleY(scale);
                // c.setle
                c.setTextSize(TypedValue.COMPLEX_UNIT_PX, c.getTextSize() * scale);

                /*
                int p1 = c.getPaddingTop();
                int p2 = c.getPaddingBottom();
                int p3 = c.getPaddingLeft();
                int p4 = c.getPaddingRight();
                c.setPadding((int) (p3/scale), p1, p4, p2);
                */
                //LevelListDrawable D = (LevelListDrawable) c.getBackground();
                /*
                Drawable d = c.getBackground();
                Log.d("bounds", d.getBounds().toString());
                */
                //d.setTargetDensity((int) (Density * scale));
                //d.setBounds(0, 0, c.getHeight(), c.getHeight());
                //lib.setBgCheckBox(c,d);
                /*
                ViewGroup check = (ViewGroup) V;
                for (int ii = 0; ii<check.getChildCount(); ii++)
                {
                   View cv = check.getChildAt(ii);
                   String cls = cv.getClass().getName();
                   Log.d("Classs", cls);
                }
                */
                // Drawable d = lib.getDefaultCheckBoxDrawable(_main);
                // d = new ScaleDrawable(d, 0, c.getHeight()*scale,
                // c.getHeight()*scale).getDrawable();
                // float scaleC = (float)c.getHeight()/d.getBounds().height();
                // d.setBounds(0, 0,(int) (c.getHeight()*scale),(int)
                // (c.getHeight()*scale));
                // LayerDrawable L = new LayerDrawable(new Drawable[]{d});
                // d = lib.scaleImage(_main, d, scaleC);
                // /c.setButtonDrawable(d);
            }
        }
        /*
        libLearn.gStatus="Buttons";
        Button b = (Button) findViewById(R.id.btnOK);
        RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) b
              .getLayoutParams();
        params.topMargin = (int) (params.topMargin * scale);
        if (params.height>0)params.height = (int) (params.height * scale);
        if (params.width>0)params.width = (int) (params.width * scale);
        b.setLayoutParams(params);
        b.setTextSize(TypedValue.COMPLEX_UNIT_PX, b.getTextSize() * scale);
                
        b = (Button) findViewById(R.id.btnCancel);
        params = (android.widget.RelativeLayout.LayoutParams) b
              .getLayoutParams();
        params.topMargin = (int) (params.topMargin * scale);
        if (params.height>0)params.height = (int) (params.height * scale);
        if (params.width>0)params.width = (int) (params.width * scale);
        b.setLayoutParams(params);
        b.setTextSize(TypedValue.COMPLEX_UNIT_PX, b.getTextSize() * scale);
        */
        SettingsView.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

                    @Override
                    public void onGlobalLayout() {
                        // Ensure you call it only once :
                        lib.removeLayoutListener(SettingsView.getViewTreeObserver(), this);
                        int pos = spnASCII.getSelectedItemPosition();
                        spnASCII.setSelection(-1);
                        spnASCII.setSelection(pos);
                    }
                });

    } catch (Exception ex) {
        lib.ShowException(_main, ex);
    } finally {
        mainView.setVisibility(View.VISIBLE);
    }

}

From source file:android.support.v7.internal.view.menu.ActionMenuPresenter.java

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

    final Resources res = context.getResources();

    final ActionBarPolicy abp = ActionBarPolicy.get(context);
    if (!mReserveOverflowSet) {
        mReserveOverflow = abp.showsOverflowMenuButton();
    }//from   w w  w  .j  a v  a2 s  . com

    if (!mWidthLimitSet) {
        mWidthLimit = abp.getEmbeddedMenuWidthLimit();
    }

    // Measure for initial configuration
    if (!mMaxItemsSet) {
        mMaxItems = abp.getMaxActionButtons();
    }

    int width = mWidthLimit;
    if (mReserveOverflow) {
        if (mOverflowButton == null) {
            mOverflowButton = new OverflowMenuButton(mSystemContext);
            final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            mOverflowButton.measure(spec, spec);
        }
        width -= mOverflowButton.getMeasuredWidth();
    } else {
        mOverflowButton = null;
    }

    mActionItemWidthLimit = width;

    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:com.bettervectordrawable.lib.graphics.drawable.VectorDrawable.java

void updateDimensionInfo(@Nullable Resources res, boolean updateConstantStateDensity) {
    if (res != null) {
        final int densityDpi = res.getDisplayMetrics().densityDpi;
        final int targetDensity = densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi;
        if (updateConstantStateDensity) {
            mVectorState.mVPathRenderer.mTargetDensity = targetDensity;
        } else {/*  w w w  . j  a  v  a  2 s .  c om*/
            final int constantStateDensity = mVectorState.mVPathRenderer.mTargetDensity;
            if (targetDensity != constantStateDensity && constantStateDensity != 0) {
                mDpiScaledWidth = BitmapExtension.scaleFromDensity((int) mVectorState.mVPathRenderer.mBaseWidth,
                        constantStateDensity, targetDensity);
                mDpiScaledHeight = BitmapExtension.scaleFromDensity(
                        (int) mVectorState.mVPathRenderer.mBaseHeight, constantStateDensity, targetDensity);
                final int left = BitmapExtension.scaleFromDensity(
                        mVectorState.mVPathRenderer.mOpticalInsets.left, constantStateDensity, targetDensity);
                final int right = BitmapExtension.scaleFromDensity(
                        mVectorState.mVPathRenderer.mOpticalInsets.right, constantStateDensity, targetDensity);
                final int top = BitmapExtension.scaleFromDensity(mVectorState.mVPathRenderer.mOpticalInsets.top,
                        constantStateDensity, targetDensity);
                final int bottom = BitmapExtension.scaleFromDensity(
                        mVectorState.mVPathRenderer.mOpticalInsets.bottom, constantStateDensity, targetDensity);
                mDpiScaleInsets = Insets.of(left, top, right, bottom);
                return;
            }
        }
    }
    // For all the other cases, like either res is null, constant state is not initialized or
    // target density is the same as the constant state, we will just use the constant state
    // dimensions.
    mDpiScaledWidth = (int) mVectorState.mVPathRenderer.mBaseWidth;
    mDpiScaledHeight = (int) mVectorState.mVPathRenderer.mBaseHeight;
    mDpiScaleInsets = mVectorState.mVPathRenderer.mOpticalInsets;
}

From source file:com.android.mylauncher3.allapps.AllAppsGridAdapter.java

public AllAppsGridAdapter(Launcher launcher, AlphabeticalAppsList apps, View.OnTouchListener touchListener,
        View.OnClickListener iconClickListener, View.OnLongClickListener iconLongClickListener) {
    Resources res = launcher.getResources();
    mLauncher = launcher;//from ww w . jav  a2s  .c om
    mApps = apps;
    mEmptySearchMessage = res.getString(R.string.all_apps_loading_message);
    mGridSizer = new GridSpanSizer();
    mGridLayoutMgr = new AppsGridLayoutManager(launcher);
    mGridLayoutMgr.setSpanSizeLookup(mGridSizer);
    mItemDecoration = new GridItemDecoration();
    mLayoutInflater = LayoutInflater.from(launcher);
    mTouchListener = touchListener;
    mIconClickListener = iconClickListener;
    mIconLongClickListener = iconLongClickListener;
    mSectionNamesMargin = res.getDimensionPixelSize(R.dimen.all_apps_grid_view_start_margin);
    mSectionHeaderOffset = res.getDimensionPixelSize(R.dimen.all_apps_grid_section_y_offset);

    mSectionTextPaint = new Paint();
    mSectionTextPaint.setTextSize(res.getDimensionPixelSize(R.dimen.all_apps_grid_section_text_size));
    mSectionTextPaint.setColor(res.getColor(R.color.all_apps_grid_section_text_color));
    mSectionTextPaint.setAntiAlias(true);

    mPredictedAppsDividerPaint = new Paint();
    mPredictedAppsDividerPaint.setStrokeWidth(Utilities.pxFromDp(1f, res.getDisplayMetrics()));
    mPredictedAppsDividerPaint.setColor(0x1E000000);
    mPredictedAppsDividerPaint.setAntiAlias(true);
    mPredictionBarDividerOffset = (-res.getDimensionPixelSize(R.dimen.all_apps_prediction_icon_bottom_padding)
            + res.getDimensionPixelSize(R.dimen.all_apps_icon_top_bottom_padding)) / 2;

    // Resolve the market app handling additional searches
    PackageManager pm = launcher.getPackageManager();
    ResolveInfo marketInfo = pm.resolveActivity(createMarketSearchIntent(""),
            PackageManager.MATCH_DEFAULT_ONLY);
    if (marketInfo != null) {
        mMarketAppName = marketInfo.loadLabel(pm).toString();
    }
}

From source file:com.geecko.QuickLyric.fragment.LyricsViewFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    MainActivity mainActivity = (MainActivity) getActivity();
    if (mainActivity == null)
        return;/*from w w w . ja v a  2  s. c o  m*/
    CollapsingToolbarLayout toolbarLayout = (CollapsingToolbarLayout) mainActivity
            .findViewById(R.id.toolbar_layout);
    toolbarLayout.setTitle(getString(R.string.app_name));

    if (((DrawerLayout) mainActivity.drawer) // drawer is locked
            .getDrawerLockMode(mainActivity.drawerView) == DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
        return;

    inflater.inflate(lyrics, menu);
    // Get the SearchView and set the searchable configuration
    final MaterialSuggestionsSearchView materialSearchView = (MaterialSuggestionsSearchView) mainActivity
            .findViewById(R.id.material_search_view);
    materialSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(final String query) {
            materialSearchView.setSuggestions(null);
            materialSearchView.requestFocus();
            materialSearchView.post(new Runnable() {
                @Override
                public void run() {
                    ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(materialSearchView.getWindowToken(), 0);
                }
            });
            materialSearchView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((MainActivity) getActivity()).search(query);
                    materialSearchView.setSuggestions(null);
                }
            }, 90);
            mExpandedSearchView = false;
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            if (!materialSearchView.hasSuggestions())
                materialSearchView.setSuggestions(materialSearchView.getHistory());
            return true;
        }
    });

    materialSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
        @Override
        public void onSearchViewShown() {
            if (getActivity() == null)
                return;
            ((ControllableAppBarLayout) getActivity().findViewById(R.id.appbar)).expandToolbar(true);
            mExpandedSearchView = true;
        }

        @Override
        public void onSearchViewClosed() {
            mExpandedSearchView = false;
        }
    });

    final Resources resources = getResources();
    final int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    int statusBarHeight;
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP)
        statusBarHeight = 0;
    else if (resourceId > 0)
        statusBarHeight = resources.getDimensionPixelSize(resourceId);
    else
        statusBarHeight = (int) Math.ceil((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? 24 : 25)
                * resources.getDisplayMetrics().density);
    CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) materialSearchView.getLayoutParams();
    lp.setMargins(lp.leftMargin, statusBarHeight, lp.rightMargin, lp.bottomMargin);
    materialSearchView.setLayoutParams(lp);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    materialSearchView.setMenuItem(searchItem);

    if (!materialSearchView.isSearchOpen() && mExpandedSearchView) {
        materialSearchView.showSearch();
        mExpandedSearchView = false;
    } else if (!mExpandedSearchView)
        materialSearchView.closeSearch();

    materialSearchView.setHint(getString(R.string.search_hint));
    if (mSearchQuery != null && !mSearchQuery.equals("")) {
        searchItem.expandActionView();
        materialSearchView.setQuery(mSearchQuery, false);
        if (mSearchFocused)
            materialSearchView.requestFocus();
        else
            materialSearchView.clearFocus();
        mSearchQuery = null;
    }
    Lyrics storedLyrics = mLyrics == null ? null
            : DatabaseHelper.getInstance(getActivity()).get(new String[] { mLyrics.getArtist(),
                    mLyrics.getTitle(), mLyrics.getOriginalArtist(), mLyrics.getOriginalTrack() });

    MenuItem saveMenuItem = menu.findItem(R.id.save_action);
    if (saveMenuItem != null) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (mLyrics == null)
            saveMenuItem.setVisible(false);
        else if (mLyrics.getFlag() == Lyrics.POSITIVE_RESULT && sharedPref.getBoolean("pref_auto_save", true)) {
            if (storedLyrics == null || (mLyrics.isLRC() && !storedLyrics.isLRC())) {
                lyricsPresentInDB = true;
                new WriteToDatabaseTask().execute(this, saveMenuItem, mLyrics);
            }
            saveMenuItem.setVisible(false);
        } else {
            saveMenuItem.setIcon(lyricsPresentInDB ? R.drawable.ic_trash : R.drawable.ic_save);
            saveMenuItem.setTitle(lyricsPresentInDB ? R.string.remove_action : R.string.save_action);
        }
    }
    MenuItem resyncMenuItem = menu.findItem(R.id.resync_action);
    MenuItem convertMenuItem = menu.findItem(R.id.convert_action);
    if (resyncMenuItem != null)
        resyncMenuItem.setVisible(mLyrics != null && mLyrics.isLRC());
    if (convertMenuItem != null) {
        Lyrics stored = mLyrics == null || mLyrics.isLRC() ? null : storedLyrics;
        convertMenuItem
                .setVisible((mLyrics != null && (mLyrics.isLRC())) || (stored != null && stored.isLRC()));
        convertMenuItem.setTitle(stored == null ? R.string.full_text_action : R.string.pref_lrc);
    }

    MenuItem shareMenuItem = menu.findItem(R.id.share_action);
    if (shareMenuItem != null)
        shareMenuItem.setVisible(
                mLyrics != null && mLyrics.getFlag() == Lyrics.POSITIVE_RESULT && mLyrics.getURL() != null);
}