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.chauthai.overscroll.BouncyAdapter.java

private double pxToDp(double px) {
    Resources resources = mContext.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    return px / ((double) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

From source file:br.liveo.searchliveo.SearchCardLiveo.java

private float dpToPixel(float dp, Context context) {
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    return dp * (metrics.densityDpi / 160f);
}

From source file:net.gsantner.opoc.util.ContextUtils.java

/**
 * Draw text in the center of the given {@link DrawableRes}
 * This may be useful for e.g. badge counts
 */// w ww  . jav  a 2  s. c o  m
public Bitmap drawTextOnDrawable(@DrawableRes int drawableRes, String text, int textSize) {
    Resources resources = _context.getResources();
    float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap = drawableToBitmap(drawableRes);

    bitmap = bitmap.copy(bitmap.getConfig(), true);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(Color.rgb(61, 61, 61));
    paint.setTextSize((int) (textSize * scale));
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    int x = (bitmap.getWidth() - bounds.width()) / 2;
    int y = (bitmap.getHeight() + bounds.height()) / 2;
    canvas.drawText(text, x, y, paint);

    return bitmap;
}

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

@Override
public void onItemSelected(AdapterView<?> adapterView, View v, int i, long l) {

    /* //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  a  v  a 2  s  .c  o  m
     */

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

    /* Changing the language to the one the user have selected based on the
     * Languages.xml file
     */
    switch (i) {
    /* English */
    case 0:
        config.locale = new Locale("en");
        break;
    /* Portuguese */
    case 1:
        config.locale = new Locale("pt");
        break;
    }

    /* Setting the new locale */
    rsc.updateConfiguration(config, rsc.getDisplayMetrics());
    refreshMessages(v);

    /* Updating the layout with the new selected language */

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

From source file:com.appsimobile.appsii.module.search.SearchController.java

@Override
protected void onViewCreated(View view, Bundle savedInstanceState) {
    mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler);
    mSearchView = (EditText) view.findViewById(R.id.search_view);
    mSuggestionsAnchor = view.findViewById(R.id.search_wrapper);
    mSearchRecyclerView = (RecyclerView) view.findViewById(R.id.search_recycler);
    mSearchDivider = view.findViewById(R.id.search_divider);

    mSearchRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));
    mSearchRecyclerView.setAdapter(mSearchSuggestionsAdapter);

    mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getContext()));
    mRecyclerView.setAdapter(mSearchAdapter);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    //        mRecyclerView.setOnScrollListener(new ToolbarScrollListener(this, mToolbar));

    Resources res = getResources();
    float density = res.getDisplayMetrics().density;

    // calculate the width of the sidebar
    int contentWidth = getContentWidth();
    if (contentWidth == 0) {
        float pct = mPreferenceHelper.getSidebarWidth() / 100f;
        contentWidth = (int) (res.getConfiguration().smallestScreenWidthDp * density * pct);
    }//  ww w  .j a v  a  2 s . com

    int dp104 = (int) (density * 104);
    int cellCount = contentWidth / dp104;
    if (cellCount < 3)
        cellCount = 3;
    if (cellCount > 3)
        cellCount--;

    mGridLayoutManager = new GridLayoutManager(getContext(), cellCount);
    mSearchAdapter.setSpanCount(cellCount);
    mRecyclerView.setLayoutManager(mGridLayoutManager);
    mGridLayoutManager.setSpanSizeLookup(mSearchAdapter.mSpanSizeLookup);

    mSearchView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            onSearchTextChanged(s);
        }
    });
    mSearchView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            onSearchFocusChanged(hasFocus);
        }
    });

    mSearchSuggestionsAdapter.setOnItemClickListener(this);

    Button speechButton;
    /*
    speechButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
    //                intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
        mSpeechRecognizer.startListening(intent);
        Log.i("111111", "11111111");
    }
    });
    */
}

From source file:org.akvo.caddisfly.ui.activity.MainActivity.java

/**
 * Load user preferences/*from  ww w  .  j av  a 2 s  . c o m*/
 */
private void loadSavedPreferences() {
    assert getApplicationContext() != null;

    // Set the locale according to preference
    Locale myLocale = new Locale(PreferencesUtils.getString(this, R.string.languageKey, Config.DEFAULT_LOCALE));
    Resources res = getResources();
    DisplayMetrics dm = res.getDisplayMetrics();
    Configuration conf = res.getConfiguration();
    conf.locale = myLocale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        conf.setLayoutDirection(myLocale);
    }
    res.updateConfiguration(conf, dm);
}

From source file:org.mythdroid.activities.Guide.java

@Override
public void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.guide);/*from   w w  w . j a v  a  2  s. c  o m*/

    hScroll = (HorizontalScrollView) findViewById(R.id.guidehscroll);
    vScroll = (ScrollView) findViewById(R.id.guidevscroll);

    Resources res = getResources();

    scale = res.getDisplayMetrics().density;

    gDetector = new GestureDetector(this, new GuideGestureListener());

    if (getWindowManager().getDefaultDisplay().getWidth() > 1000
            || getWindowManager().getDefaultDisplay().getHeight() > 1000)
        numHours *= 2;

    numTimes = numHours * 60 / colMins;

    times = new long[numTimes + 1];
    hdrTimes = new String[numTimes / hdrSpan];

    colWidth = (int) (40 * scale + 0.5f);
    rowHeight = (int) (60 * scale + 0.5f);
    chanWidth = (int) (100 * scale + 0.5f);

    tbl = (TableLayout) findViewById(R.id.table);

    rowLayout.topMargin = rowLayout.bottomMargin = chanLayout.topMargin = chanLayout.bottomMargin = chanLayout.leftMargin = chanLayout.rightMargin = hdrDateLayout.leftMargin = hdrDateLayout.rightMargin = hdrTimeLayout.leftMargin = hdrTimeLayout.rightMargin = 1;

    rowLayout.height = chanLayout.height = rowHeight;

    chanLayout.column = hdrDateLayout.column = 0;
    chanLayout.span = hdrDateLayout.span = 1;
    chanLayout.width = hdrDateLayout.width = chanWidth;

    hdrTimeLayout.width = colWidth * hdrSpan;
    hdrTimeLayout.span = hdrSpan;

    spacerLayout.height = 1;
    spacerLayout.width = colWidth;
    spacerLayout.span = 1;

    recordedIcon = res.getDrawable(R.drawable.recorded);
    willRecordIcon = res.getDrawable(R.drawable.willrecord);
    failedIcon = res.getDrawable(R.drawable.failed);
    conflictIcon = res.getDrawable(R.drawable.conflict);
    otherIcon = res.getDrawable(R.drawable.other);

    date.setTimeZone(TimeZone.getDefault());
    time.setTimeZone(TimeZone.getDefault());

    if (Globals.haveServices())
        try {
            guideService = new GuideService(Globals.getBackend().addr);
        } catch (IOException e) {
            ErrUtil.err(this, e);
            finish();
            return;
        }

}

From source file:com.mjhram.geodata.GpsMainActivity.java

public Bitmap drawMultilineTextToBitmap(Context gContext, Bitmap bitmap, String gText) {
    // prepare canvas
    Resources resources = gContext.getResources();
    float scale = resources.getDisplayMetrics().density;
    //Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }/*  w  w w . j  av a  2 s. co  m*/
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);

    Canvas canvas = new Canvas(bitmap);

    // new antialiased Paint
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(61, 61, 61));
    // text size in pixels
    paint.setTextSize((int) (20 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
    //canvas.drawText("This is", 100, 100, paint);
    //canvas.drawText("multi-line", 100, 150, paint);
    //canvas.drawText("text", 100, 200, paint);

    // set text width to canvas width minus 16dp padding
    int textWidth = canvas.getWidth() - (int) (16 * scale);

    // init StaticLayout for text
    StaticLayout textLayout = new StaticLayout(gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f,
            0.0f, false);

    // get height of multiline text
    int textHeight = textLayout.getHeight();

    // get position of text's top left corner
    float x = (bitmap.getWidth() - textWidth) / 2;
    float y = bitmap.getHeight() - textHeight;

    // draw text to the Canvas center
    canvas.save();
    canvas.translate(x, y);
    textLayout.draw(canvas);
    canvas.restore();

    return bitmap;
}

From source file:com.actionbarsherlock.widget.ActivityChooserView.java

/**
 * Create a new instance.//from www . j a  v a 2  s  . c om
 *
 * @param context The application environment.
 * @param attrs A collection of attributes.
 * @param defStyle The default style to apply to this view.
 */
public ActivityChooserView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    mContext = context;

    TypedArray attributesArray = context.obtainStyledAttributes(attrs, R.styleable.SherlockActivityChooserView,
            defStyle, 0);

    mInitialActivityCount = attributesArray.getInt(R.styleable.SherlockActivityChooserView_initialActivityCount,
            ActivityChooserViewAdapter.MAX_ACTIVITY_COUNT_DEFAULT);

    Drawable expandActivityOverflowButtonDrawable = attributesArray
            .getDrawable(R.styleable.SherlockActivityChooserView_expandActivityOverflowButtonDrawable);

    attributesArray.recycle();

    LayoutInflater inflater = LayoutInflater.from(mContext);
    inflater.inflate(R.layout.abs__activity_chooser_view, this, true);

    mCallbacks = new Callbacks();

    mActivityChooserContent = (IcsLinearLayout) findViewById(R.id.abs__activity_chooser_view_content);
    mActivityChooserContentBackground = mActivityChooserContent.getBackground();

    mDefaultActivityButton = (FrameLayout) findViewById(R.id.abs__default_activity_button);
    mDefaultActivityButton.setOnClickListener(mCallbacks);
    mDefaultActivityButton.setOnLongClickListener(mCallbacks);
    mDefaultActivityButtonImage = (ImageView) mDefaultActivityButton.findViewById(R.id.abs__image);

    mExpandActivityOverflowButton = (FrameLayout) findViewById(R.id.abs__expand_activities_button);
    mExpandActivityOverflowButton.setOnClickListener(mCallbacks);
    mExpandActivityOverflowButtonImage = (ImageView) mExpandActivityOverflowButton
            .findViewById(R.id.abs__image);
    mExpandActivityOverflowButtonImage.setImageDrawable(expandActivityOverflowButtonDrawable);

    mAdapter = new ActivityChooserViewAdapter();
    mAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            updateAppearance();
        }
    });

    Resources resources = context.getResources();
    mListPopupMaxWidth = Math.max(resources.getDisplayMetrics().widthPixels / 2,
            resources.getDimensionPixelSize(R.dimen.abs__config_prefDialogWidth));
}

From source file:org.mariotaku.twidere.fragment.support.AccountsDashboardFragment.java

private void updateAccountOptionsSeparatorLabel(Drawable profileImageSnapshot) {
    final ParcelableAccount account = mAccountsAdapter.getSelectedAccount();
    if (account == null) {
        return;/*from w  w  w  . ja  v  a  2  s.c o  m*/
    }
    mAccountProfileNameView.setText(account.name);
    mAccountProfileScreenNameView.setText("@" + account.screen_name);
    mImageLoader.displayDashboardProfileImage(mAccountProfileImageView, account.profile_image_url,
            profileImageSnapshot);
    mAccountProfileImageView.setBorderColors(account.color);
    final int bannerWidth = mAccountProfileBannerView.getWidth();
    final Resources res = getResources();
    final int defWidth = res.getDisplayMetrics().widthPixels;
    final int width = bannerWidth > 0 ? bannerWidth : defWidth;
    final String bannerUrl = Utils.getBestBannerUrl(account.profile_banner_url, width);
    final ImageView bannerView = mAccountProfileBannerView;
    if (bannerView.getDrawable() == null || !CompareUtils.objectEquals(bannerUrl, bannerView.getTag())) {
        mImageLoader.displayProfileBanner(mAccountProfileBannerView, bannerUrl, this);
    } else {
        mImageLoader.cancelDisplayTask(mAccountProfileBannerView);
    }
}