Example usage for android.util TypedValue applyDimension

List of usage examples for android.util TypedValue applyDimension

Introduction

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

Prototype

public static float applyDimension(int unit, float value, DisplayMetrics metrics) 

Source Link

Document

Converts an unpacked complex data value holding a dimension to its final floating point value.

Usage

From source file:cn.scujcc.bug.bitcoinplatformandroid.fragment.OrderFragment.java

@Nullable
@Override//from  w w w .  j  a  v  a 2s . c  om
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmnet_quotationinformation, container, false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);

    mNoneText = (TextView) view.findViewById(R.id.none_text);

    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);

    mSwipeRefreshWidget.setOnRefreshListener(this);

    mSwipeRefreshWidget.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);

    mSwipeRefreshWidget.setProgressViewOffset(false, 0, (int) TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

    setTitle(view, "?");

    return view;
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.fragment.QuotationInformationFragment.java

@Nullable
@Override//  w  w w. j  a v  a2s  .com
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragmnet_quotationinformation, container, false);

    setHasOptionsMenu(true);
    setTitle(view, "");

    mNoneText = (TextView) view.findViewById(R.id.none_text);

    mSwipeRefreshWidget = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);

    mSwipeRefreshWidget.setOnRefreshListener(this);

    mSwipeRefreshWidget.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark);

    mSwipeRefreshWidget.setProgressViewOffset(false, 0, (int) TypedValue
            .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

    mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);

    //???,?
    mRecyclerView.setHasFixedSize(true);

    // 
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);

    //Adapter
    mAdapter = new CardAdapter();
    mRecyclerView.setAdapter(mAdapter);

    //??
    NewsAsyncTask task = new NewsAsyncTask();
    task.execute();

    mSwipeRefreshWidget.setRefreshing(true);

    return view;
}

From source file:au.com.zacher.popularmovies.activity.layout.CollapsingTitleLayout.java

/**
 * Recursive binary search to find the best size for the text
 *
 * Adapted from https://github.com/grantland/android-autofittextview
 *///from w w  w . j a  v  a2 s  . com
private static float getSingleLineTextSize(String text, TextPaint paint, float targetWidth, float low,
        float high, float precision, DisplayMetrics metrics) {
    final float mid = (low + high) / 2.0f;

    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, metrics));
    final float maxLineWidth = paint.measureText(text);

    if ((high - low) < precision) {
        return low;
    } else if (maxLineWidth > targetWidth) {
        return getSingleLineTextSize(text, paint, targetWidth, low, mid, precision, metrics);
    } else if (maxLineWidth < targetWidth) {
        return getSingleLineTextSize(text, paint, targetWidth, mid, high, precision, metrics);
    } else {
        return mid;
    }
}

From source file:com.skytree.epubtest.BookViewActivity.java

public int getPSFromDP(float dps) {
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, metrics);
    return (int) pixels;
}

From source file:android.support.v7.widget.AppCompatTextViewAutoSizeHelper.java

/**
 * Specify whether this widget should automatically scale the text to try to perfectly fit
 * within the layout bounds. If at least one value from the <code>presetSizes</code> is valid
 * then the type of auto-size is set to {@link TextViewCompat#AUTO_SIZE_TEXT_TYPE_UNIFORM}.
 *
 * @param presetSizes an {@code int} array of sizes in pixels
 * @param unit the desired dimension unit for the preset sizes above. See {@link TypedValue} for
 *             the possible dimension units
 *
 * @throws IllegalArgumentException if all of the <code>presetSizes</code> are invalid.
 *_//from   w  w  w .  j a  v  a 2 s.  c  o m
 * @attr ref R.styleable#AppCompatTextView_autoSizeTextType
 * @attr ref R.styleable#AppCompatTextView_autoSizePresetSizes
 *
 * @see #setAutoSizeTextTypeWithDefaults(int)
 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int)
 * @see #getAutoSizeMinTextSize()
 * @see #getAutoSizeMaxTextSize()
 * @see #getAutoSizeTextAvailableSizes()
 *
 * @hide
 */
@RestrictTo(LIBRARY_GROUP)
void setAutoSizeTextTypeUniformWithPresetSizes(@NonNull int[] presetSizes, int unit)
        throws IllegalArgumentException {
    if (supportsAutoSizeText()) {
        final int presetSizesLength = presetSizes.length;
        if (presetSizesLength > 0) {
            int[] presetSizesInPx = new int[presetSizesLength];

            if (unit == TypedValue.COMPLEX_UNIT_PX) {
                presetSizesInPx = Arrays.copyOf(presetSizes, presetSizesLength);
            } else {
                final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
                // Convert all to sizes to pixels.
                for (int i = 0; i < presetSizesLength; i++) {
                    presetSizesInPx[i] = Math
                            .round(TypedValue.applyDimension(unit, presetSizes[i], displayMetrics));
                }
            }

            mAutoSizeTextSizesInPx = cleanupAutoSizePresetSizes(presetSizesInPx);
            if (!setupAutoSizeUniformPresetSizesConfiguration()) {
                throw new IllegalArgumentException(
                        "None of the preset sizes is valid: " + Arrays.toString(presetSizes));
            }
        } else {
            mHasPresetAutoSizeValues = false;
        }

        if (setupAutoSizeText()) {
            autoSizeText();
        }
    }
}

From source file:fr.cph.chicago.util.Util.java

public static int convertDpToPixel(@NonNull final Context context, final int dp) {
    float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
            context.getResources().getDisplayMetrics());
    return (int) pixels;
}

From source file:com.easemob.easeui.widget.viewpagerindicator.PagerSlidingTabStrip.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (isInEditMode() || tabCount == 0 || !isNeedToDoDraw) {
        return;// www.  ja va  2 s.c  o m
    }

    final int height = getHeight();

    // draw underline
    rectPaint.setColor(underlineColor);
    canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);

    // draw indicator line
    rectPaint.setColor(indicatorColor);

    // default: line below current tab
    View currentTab = tabsContainer.getChildAt(currentPosition);
    float lineLeft = currentTab.getLeft();
    float lineRight = currentTab.getRight();

    // if there is an offset, start interpolating left and right coordinates between current and next tab
    if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {

        View nextTab = tabsContainer.getChildAt(currentPosition + 1);
        final float nextTabLeft = nextTab.getLeft();
        final float nextTabRight = nextTab.getRight();

        lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
        lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
    }

    canvas.drawRect(
            lineLeft - (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, EaseUI.displayMetrics),
            height - indicatorHeight,
            lineRight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, EaseUI.displayMetrics),
            height, rectPaint);

    //        draw divider

    dividerPaint.setColor(dividerColor);
    //        for (int i = 0; i < tabCount - 1; i++) {
    //            View tab = tabsContainer.getChildAt(i);
    //            canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding,
    //                    dividerPaint);
    //        }

}

From source file:ca.zadrox.dota2esportticker.ui.LiveContentView.java

private void initMapView() {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

    int minHeight = displayMetrics.widthPixels > displayMetrics.heightPixels
            ? displayMetrics.heightPixels - UIUtils.calculateActionBarSize(this)
            : displayMetrics.widthPixels;

    mapX = mapY = minHeight - getResources().getDimensionPixelSize(R.dimen.keyline_1) * 2;

    Picasso.with(this).load(R.drawable.dota2_map).config(Bitmap.Config.RGB_565).resize(mapX, mapY).into(mapView,
            mLoadMapCallback);//from  w  ww . j a va 2 s .co m

    for (int i = 0; i < DotaMapModel.DIRE_TOWERS.length; i++) {
        int x = DotaMapModel.scaleToNewMapSize(DotaMapModel.DIRE_TOWERS_X[i], mapX);
        int y = DotaMapModel.scaleToNewMapSize(DotaMapModel.DIRE_TOWERS_Y[i], mapY);

        View v = findViewById(DotaMapModel.DIRE_TOWERS[i]);
        v.setX(x);
        v.setY(y);
        v.setBackground(getResources().getDrawable(R.drawable.dire_tower));
    }

    for (int i = 0; i < DotaMapModel.DIRE_STRUCTURES.length; i++) {
        int x = DotaMapModel.scaleToNewMapSize(DotaMapModel.DIRE_STRUCTURES_X[i], mapX);
        int y = DotaMapModel.scaleToNewMapSize(DotaMapModel.DIRE_STRUCTURES_Y[i], mapY);

        View v = findViewById(DotaMapModel.DIRE_STRUCTURES[i]);
        v.setX(x);
        v.setY(y);
        v.setBackground(getResources().getDrawable(R.drawable.dire_hero_oval));
    }

    for (int i = 0; i < DotaMapModel.RADIANT_TOWERS.length; i++) {
        int x = DotaMapModel.scaleToNewMapSize(DotaMapModel.RADIANT_TOWERS_X[i], mapX);
        int y = DotaMapModel.scaleToNewMapSize(DotaMapModel.RADIANT_TOWERS_Y[i], mapY);

        View v = findViewById(DotaMapModel.RADIANT_TOWERS[i]);
        v.setX(x);
        v.setY(y);
        v.setBackground(getResources().getDrawable(R.drawable.radiant_tower));
    }

    for (int i = 0; i < DotaMapModel.RADIANT_STRUCTURES.length; i++) {
        int x = DotaMapModel.scaleToNewMapSize(DotaMapModel.RADIANT_STRUCTURES_X[i], mapX);
        int y = DotaMapModel.scaleToNewMapSize(DotaMapModel.RADIANT_STRUCTURES_Y[i], mapY);

        View v = findViewById(DotaMapModel.RADIANT_STRUCTURES[i]);
        v.setX(x);
        v.setY(y);
        v.setBackground(getResources().getDrawable(R.drawable.radiant_hero_oval));
    }

    final int iconSizeRoshan = Math.round(
            TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()));

    ImageView v = (ImageView) findViewById(DotaMapModel.ROSHAN);
    v.setX(DotaMapModel.scaleToNewMapSize(DotaMapModel.ROSHAN_X, mapX));
    v.setY(DotaMapModel.scaleToNewMapSize(DotaMapModel.ROSHAN_Y, mapY));

    Picasso.with(this).load(R.drawable.drawable_map_roshan).resize(iconSizeRoshan, iconSizeRoshan).centerCrop()
            .into(v);
}

From source file:ch.gianulli.flashcards.ui.Flashcard.java

/**
 * @return the font size measured in px//from  w  w w  . j  ava2s .  c o  m
 */
public int getFontSizeInPx() {
    DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mFontSize, metrics);
}

From source file:com.oonhee.oojs.inappbrowser.InAppBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from w w w. j  a v  a2s.c om*/
 */
public String showWebPage(final String url, HashMap<String, Boolean> features) {
    // Determine if we should hide the location bar.
    showLocationBar = true;
    openWindowHidden = false;
    if (features != null) {
        Boolean show = features.get(LOCATION);
        if (show != null) {
            showLocationBar = show.booleanValue();
        }
        Boolean hidden = features.get(HIDDEN);
        if (hidden != null) {
            openWindowHidden = hidden.booleanValue();
        }
        Boolean cache = features.get(CLEAR_ALL_CACHE);
        if (cache != null) {
            clearAllCache = cache.booleanValue();
        } else {
            cache = features.get(CLEAR_SESSION_CACHE);
            if (cache != null) {
                clearSessionCache = cache.booleanValue();
            }
        }
    }

    final CordovaWebView thatWebView = this.webView;

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    closeDialog();
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            //Please, no more black! 
            toolbar.setBackgroundColor(android.graphics.Color.LTGRAY);
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            Button back = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setText("<");
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            Button forward = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setText(">");
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            Button close = new Button(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setText(buttonLabel);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            inAppWebView = new AmazonWebView(cordova.getActivity());

            CordovaActivity app = (CordovaActivity) cordova.getActivity();
            cordova.getFactory().initializeWebView(inAppWebView, 0x00FF00, false, null);

            inAppWebView.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
            AmazonWebViewClient client = new InAppBrowserClient(thatWebView, edittext);
            inAppWebView.setWebViewClient(client);
            AmazonWebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginState(com.amazon.android.webkit.AmazonWebSettings.PluginState.ON);

            //Toggle whether this is enabled or not!
            Bundle appSettings = cordova.getActivity().getIntent().getExtras();
            boolean enableDatabase = appSettings == null ? true
                    : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
            if (enableDatabase) {
                String databasePath = cordova.getActivity().getApplicationContext()
                        .getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
                settings.setDatabasePath(databasePath);
                settings.setDatabaseEnabled(true);
            }
            settings.setDomStorageEnabled(true);

            if (clearAllCache) {
                AmazonCookieManager.getInstance().removeAllCookie();
            } else if (clearSessionCache) {
                AmazonCookieManager.getInstance().removeSessionCookie();
            }

            inAppWebView.loadUrl(url);
            inAppWebView.setId(6);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
            // the goal of openhidden is to load the url and not display it
            // Show() needs to be called to cause the URL to be loaded
            if (openWindowHidden) {
                dialog.hide();
            }
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}