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:com.nextgis.maplibui.formcontrol.DoubleCombobox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {
    mSubCombobox = new Spinner(getContext());
    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_LEVEL1_KEY);
    mSubFieldName = attributes.getString(JSON_FIELD_LEVEL2_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;// w w w  .  j av  a 2s .co m
    String subLastValue = null;
    if (ControlHelper.hasKey(savedState, mFieldName) && ControlHelper.hasKey(savedState, mSubFieldName)) {
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
        subLastValue = savedState.getString(ControlHelper.getSavedStateKey(mSubFieldName));
    } else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        int subColumn = featureCursor.getColumnIndex(mSubFieldName);
        if (column >= 0)
            lastValue = featureCursor.getString(column);
        if (subColumn >= 0)
            subLastValue = featureCursor.getString(subColumn);
    } else if (mIsShowLast) {
        lastValue = preferences.getString(mFieldName, null);
        subLastValue = preferences.getString(mSubFieldName, null);
    }

    JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
    int defaultPosition = 0;
    int lastValuePosition = -1;
    int subLastValuePosition = -1;
    mAliasValueMap = new HashMap<>();
    mSubAliasValueMaps = new HashMap<>();
    mAliasSubListMap = new HashMap<>();

    final ArrayAdapter<String> comboboxAdapter = new ArrayAdapter<>(getContext(),
            R.layout.formtemplate_double_spinner);
    setAdapter(comboboxAdapter);

    if (values != null) {
        for (int j = 0; j < values.length(); j++) {
            JSONObject keyValue = values.getJSONObject(j);
            String value = keyValue.getString(JSON_VALUE_NAME_KEY);
            String valueAlias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

            Map<String, String> subAliasValueMap = new HashMap<>();
            AliasList subAliasList = new AliasList();

            mAliasValueMap.put(valueAlias, value);
            mSubAliasValueMaps.put(valueAlias, subAliasValueMap);
            mAliasSubListMap.put(valueAlias, subAliasList);
            comboboxAdapter.add(valueAlias);

            if (keyValue.has(JSON_DEFAULT_KEY) && keyValue.getBoolean(JSON_DEFAULT_KEY))
                defaultPosition = j;

            if (null != lastValue && lastValue.equals(value)) // if modify data
                lastValuePosition = j;

            JSONArray subValues = keyValue.getJSONArray(JSON_VALUES_KEY);
            for (int k = 0; k < subValues.length(); k++) {
                JSONObject subKeyValue = subValues.getJSONObject(k);
                String subValue = subKeyValue.getString(JSON_VALUE_NAME_KEY);
                String subValueAlias = subKeyValue.getString(JSON_VALUE_ALIAS_KEY);

                subAliasValueMap.put(subValueAlias, subValue);
                subAliasList.aliasList.add(subValueAlias);

                if (subKeyValue.has(JSON_DEFAULT_KEY) && subKeyValue.getBoolean(JSON_DEFAULT_KEY))
                    subAliasList.defaultPosition = k;

                if (null != subLastValue && subLastValue.equals(subValue)) { // if modify data
                    lastValuePosition = j;
                    subLastValuePosition = k;
                }
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);
    final int subLastValuePositionFinal = subLastValuePosition;

    // The drop down view
    comboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    float minHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
            getResources().getDisplayMetrics());
    setPadding(0, (int) minHeight, 0, (int) minHeight);
    mSubCombobox.setPadding(0, (int) minHeight, 0, (int) minHeight);

    setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedValueAlias = comboboxAdapter.getItem(position);
            AliasList subAliasList = mAliasSubListMap.get(selectedValueAlias);

            ArrayAdapter<String> subComboboxAdapter = new ArrayAdapter<>(view.getContext(),
                    R.layout.formtemplate_double_spinner, subAliasList.aliasList);
            subComboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            mSubCombobox.setAdapter(subComboboxAdapter);
            mSubCombobox.setSelection(mFirstShow && subLastValuePositionFinal >= 0 ? subLastValuePositionFinal
                    : subAliasList.defaultPosition);

            if (mFirstShow) {
                mFirstShow = false;
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}

From source file:com.cloverstudio.spika.SpikaApp.java

/**
 * Sets sliding transport based on screen density and required offset width
 * <p>/*from www  .  ja v a2  s .  c o  m*/
 * Depends on width of side offset in dp
 * 
 * @param sideWidthInDp
 */
public static void setTransportBasedOnScreenDensity(int sideWidthInDp) {
    WindowManager wm = (WindowManager) sInstance.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);

    double sideWidthInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sideWidthInDp,
            sInstance.getResources().getDisplayMetrics());

    double transportRate = 1 - sideWidthInPx / metrics.widthPixels;
    sInstance.mTransport = (int) Math.floor(metrics.widthPixels * transportRate);
}

From source file:codepath.watsiapp.utils.Util.java

public static float getPixels(Activity activity, float dp) {
    Resources r = activity.getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    return px;/*from  www.  j  av  a2s  . c o m*/
}

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

void loadFromAttributes(AttributeSet attrs, int defStyleAttr) {
    float autoSizeMinTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;
    float autoSizeMaxTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;
    float autoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;

    TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.AppCompatTextView, defStyleAttr, 0);
    if (a.hasValue(R.styleable.AppCompatTextView_autoSizeTextType)) {
        mAutoSizeTextType = a.getInt(R.styleable.AppCompatTextView_autoSizeTextType,
                TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);
    }/*from ww  w  .j av  a  2 s .com*/
    if (a.hasValue(R.styleable.AppCompatTextView_autoSizeStepGranularity)) {
        autoSizeStepGranularityInPx = a.getDimension(R.styleable.AppCompatTextView_autoSizeStepGranularity,
                UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE);
    }
    if (a.hasValue(R.styleable.AppCompatTextView_autoSizeMinTextSize)) {
        autoSizeMinTextSizeInPx = a.getDimension(R.styleable.AppCompatTextView_autoSizeMinTextSize,
                UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE);
    }
    if (a.hasValue(R.styleable.AppCompatTextView_autoSizeMaxTextSize)) {
        autoSizeMaxTextSizeInPx = a.getDimension(R.styleable.AppCompatTextView_autoSizeMaxTextSize,
                UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE);
    }
    if (a.hasValue(R.styleable.AppCompatTextView_autoSizePresetSizes)) {
        final int autoSizeStepSizeArrayResId = a
                .getResourceId(R.styleable.AppCompatTextView_autoSizePresetSizes, 0);
        if (autoSizeStepSizeArrayResId > 0) {
            final TypedArray autoSizePreDefTextSizes = a.getResources()
                    .obtainTypedArray(autoSizeStepSizeArrayResId);
            setupAutoSizeUniformPresetSizes(autoSizePreDefTextSizes);
            autoSizePreDefTextSizes.recycle();
        }
    }
    a.recycle();

    if (supportsAutoSizeText()) {
        if (mAutoSizeTextType == TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM) {
            // If uniform auto-size has been specified but preset values have not been set then
            // replace the auto-size configuration values that have not been specified with the
            // defaults.
            if (!mHasPresetAutoSizeValues) {
                final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();

                if (autoSizeMinTextSizeInPx == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) {
                    autoSizeMinTextSizeInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                            DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP, displayMetrics);
                }

                if (autoSizeMaxTextSizeInPx == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) {
                    autoSizeMaxTextSizeInPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                            DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP, displayMetrics);
                }

                if (autoSizeStepGranularityInPx == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) {
                    autoSizeStepGranularityInPx = DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX;
                }

                validateAndSetAutoSizeTextTypeUniformConfiguration(autoSizeMinTextSizeInPx,
                        autoSizeMaxTextSizeInPx, autoSizeStepGranularityInPx);
            }

            setupAutoSizeText();
        }
    } else {
        mAutoSizeTextType = TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE;
    }
}

From source file:com.phonegap.plugins.ChildBrowser.java

/**
* Display a new browser with the specified URL.
*
* @param url The url to load./*from   w  w  w  .  ja  v  a 2 s.c o m*/
* @param jsonObject
*/
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // 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) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_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);
            toolbar.setVisibility(View.GONE);

            // 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);
            actionButtonContainer.setVisibility(View.GONE);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/images/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/images/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            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.FILL_PARENT, LayoutParams.FILL_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
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/images/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.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(webview);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:codepath.watsiapp.utils.Util.java

public static float getPixelsFont(Activity activity, float sp) {
    Resources r = activity.getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, r.getDisplayMetrics());
    return px;//w  ww .jav a 2  s .  c  o m
}

From source file:mobi.monaca.framework.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject//from w ww  .  jav  a 2 s  .c o m
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // 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) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

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

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_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
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setImageResource(R.drawable.childbroswer_icon_arrow_left);
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setImageResource(R.drawable.childbroswer_icon_arrow_right);
            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.FILL_PARENT, LayoutParams.FILL_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
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setImageResource(R.drawable.childbroswer_icon_close);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.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(webview);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            //TODO check LocalFileBootloader
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.raspi.chatapp.util.Notification.java

private Bitmap getLargeIcon(char letter) {
    Random random = new Random();
    int widthDP = 64;
    int bgColor = Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        return getLargeIcon(bgColor, letter, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthDP,
                context.getResources().getDisplayMetrics()), true);
    else/* w  w w .  j  a v a  2s. c  o m*/
        return getLargeIcon(bgColor, letter, TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthDP,
                context.getResources().getDisplayMetrics()), false);
}

From source file:com.brq.wallet.activity.modern.AccountsFragment.java

private int getDipValue(int dip) {
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
            getResources().getDisplayMetrics());
}

From source file:com.dhaval.mobile.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject //from  ww w  . j  a  va  2  s . c  om
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
        showAddressBar = options.optBoolean("showAddressBar", true);
    }

    // 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,
                    ctx.getContext().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(ctx.getContext(), 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) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_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(ctx.getContext());
            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
            ImageButton back = new ImageButton(ctx.getContext());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(ctx.getContext());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(ctx.getContext());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_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;
                }
            });
            if (!showAddressBar) {
                edittext.setVisibility(EditText.INVISIBLE);
            }

            // Close button
            ImageButton close = new ImageButton(ctx.getContext());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(ctx.getContext());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.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(webview);

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

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}