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:edu.rowan.app.carousel.CarouselFeature.java

private void setupView() {
    imageView.setId(1);/*  w  ww . j  a  v a  2 s .c  o m*/
    RelativeLayout.LayoutParams imageParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.FILL_PARENT);
    imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
    imageView.setLayoutParams(imageParams);
    //      imageView.setAdjustViewBounds(true);
    Resources r = context.getResources();
    int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());

    TextView descriptionView = new TextView(context);
    descriptionView.setId(2);
    descriptionView.setPadding(padding, 0, padding, padding);
    descriptionView.setText(description);
    descriptionView.setBackgroundColor(Color.argb(220, 63, 26, 10));
    descriptionView.setTextColor(Color.WHITE);
    RelativeLayout.LayoutParams descParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    descParams.addRule(RelativeLayout.ALIGN_BOTTOM, imageView.getId());
    carouselView.addView(descriptionView, descParams);

    TextView titleView = new TextView(context);
    titleView.setText(title);
    titleView.setPadding(padding, 0, padding, 0);
    RelativeLayout.LayoutParams titleParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    titleParams.addRule(RelativeLayout.ABOVE, descriptionView.getId());
    titleView.setLayoutParams(titleParams);
    titleView.setTextColor(Color.WHITE);
    titleView.setShadowLayer(2, 3, 3, Color.argb(230, 0, 0, 0));
    titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 22);

    carouselView.addView(titleView);
}

From source file:agronet.mpayer.zegetech.com.mpayercashbox.fragments.HomeMenuFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    switch (position) {
    case 0:/*from   w  ww .  j a va2s  .c o m*/
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        TextView tv = (TextView) view.findViewById(R.id.orders);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnOrders = (ImageView) view.findViewById(R.id.ordersBtn);
        btnOrders.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), OrdersActivity.class);
                startActivity(i);
            }
        });
        tv = (TextView) view.findViewById(R.id.transactions);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnTransactions = (ImageView) view.findViewById(R.id.transactionsBtn);
        btnTransactions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), TransactionsActivity.class);
                startActivity(i);
            }
        });

        tv = (TextView) view.findViewById(R.id.accounts);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnAccounts = (ImageView) view.findViewById(R.id.accountsBtn);
        btnAccounts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), AccountsActivity.class);
                startActivity(i);
            }
        });

        tv = (TextView) view.findViewById(R.id.members);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnMembers = (ImageView) view.findViewById(R.id.membersBtn);
        btnMembers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), MembersActivity.class);
                startActivity(i);
            }
        });

        tv = (TextView) view.findViewById(R.id.reports);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnReports = (ImageView) view.findViewById(R.id.reportsBtn);
        btnReports.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), ReportsActivity.class);
                startActivity(i);
            }
        });

        tv = (TextView) view.findViewById(R.id.settings);
        tv.setTypeface(Constants.getCustomFace(getActivity(), "Open"));

        ImageView btnSettings = (ImageView) view.findViewById(R.id.settingsBtn);
        btnSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), SettingsActivity.class);
                startActivity(i);
            }
        });
        return view;
    case 1:
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        FrameLayout fl = new FrameLayout(getActivity());

        fl.setLayoutParams(params);

        final int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8,
                getResources().getDisplayMetrics());
        TextView v = new TextView(getActivity());
        params.setMargins(margin, margin, margin, margin);
        v.setLayoutParams(params);
        v.setLayoutParams(params);
        v.setGravity(Gravity.CENTER);
        v.setText("LOG");

        fl.addView(v);
        return fl;
    }
    return null;
}

From source file:com.commit451.springy.CompanionWatchFaceConfigActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().getDecorView()/*from   w  w w . j a  va 2s.  c  o m*/
            .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
    setContentView(R.layout.config_activity);

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Set up general chrome
    ImageButton doneButton = (ImageButton) findViewById(R.id.done_button);
    doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    ScrimInsetsFrameLayout scrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(
            R.id.scrim_insets_frame_layout);
    scrimInsetsFrameLayout.setOnInsetsCallback(new ScrimInsetsFrameLayout.OnInsetsCallback() {
        @Override
        public void onInsetsChanged(Rect insets) {
            findViewById(R.id.chrome_container).setPadding(0, insets.top, 0, 0);
        }
    });

    // Set up theme list
    mMainClockContainerView = (ViewGroup) ((ViewGroup) findViewById(R.id.clock_container)).getChildAt(0);
    mMainClockView = (SpringyNumberView) mMainClockContainerView.findViewById(R.id.clock);

    mAnimateClockContainerView = (ViewGroup) ((ViewGroup) findViewById(R.id.clock_container)).getChildAt(1);
    mAnimateClockView = (SpringyNumberView) mAnimateClockContainerView.findViewById(R.id.clock);

    mAnimateClockContainerView.setVisibility(View.INVISIBLE);

    setupThemeList();
    String themeId = mSharedPreferences.getString(ConfigHelper.KEY_THEME, Themes.DEFAULT_THEME.id);
    updateUIToSelectedTheme(themeId, false);

    registerSharedPrefsListener();

    // Set up complications config fragment
    mConfigComplicationsFragment = (ConfigComplicationsFragment) getFragmentManager()
            .findFragmentById(R.id.config_complications_container);
    if (mConfigComplicationsFragment == null) {
        mConfigComplicationsFragment = new ConfigComplicationsFragment();
        getFragmentManager().beginTransaction()
                .add(R.id.config_complications_container, mConfigComplicationsFragment).commit();
    }

    // Set up tabs/pager
    final ViewPager pager = (ViewPager) findViewById(R.id.view_pager);
    pager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
            getResources().getDisplayMetrics()));

    SimplePagerHelper helper = new SimplePagerHelper(this, pager);
    helper.addPage(R.string.title_theme, R.id.config_theme_container);
    helper.addPage(R.string.title_complications, R.id.config_complications_container);

    TabLayout slidingTabLayout = (TabLayout) findViewById(R.id.tabs);
    slidingTabLayout.setupWithViewPager(pager);

    pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            float translationX = -pager.getWidth();
            if (position == 0) {
                translationX = -positionOffsetPixels;
            }
            mMainClockView.setTranslationX(translationX);
            mAnimateClockView.setTranslationX(translationX);
        }
    });

    mTime = new Time();
    mTimerHandler = new Handler();

    mTimeChecker.run();
}

From source file:com.astuetz.PagerSlidingTabStripPlus.java

public PagerSlidingTabStripPlus(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    setFillViewport(true); // ScrollView stretch his content height to fill his viewport
    setWillNotDraw(false);//from w  w  w.  j  a  va 2  s.co m

    // Layout parameters
    tabsContainer = new LinearLayout(context);
    tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
    tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    addView(tabsContainer);

    DisplayMetrics dm = getResources().getDisplayMetrics();

    // Converting values to floating point value
    scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
    indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
    underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
    dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
    tabPaddingLeft = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPaddingLeft, dm);
    tabPaddingRight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPaddingRight, dm);
    tabPaddingTop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPaddingTop, dm);
    tabPaddingBottom = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPaddingBottom, dm);
    dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
    tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);

    // get system attrs (android:textSize and android:textColor)

    TypedArray a = context.obtainStyledAttributes(attrs, ATTRS);

    tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
    tabTextColor = a.getColor(1, tabTextColor);

    a.recycle();

    // get custom attrs

    a = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStripPlus);

    indicatorColor = a.getColor(R.styleable.PagerSlidingTabStripPlus_pstsIndicatorColor, indicatorColor);
    underlineColor = a.getColor(R.styleable.PagerSlidingTabStripPlus_pstsUnderlineColor, underlineColor);
    dividerColor = a.getColor(R.styleable.PagerSlidingTabStripPlus_pstsDividerColor, dividerColor);
    indicatorHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsIndicatorHeight,
            indicatorHeight);
    underlineHeight = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsUnderlineHeight,
            underlineHeight);
    dividerPadding = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsDividerPadding,
            dividerPadding);
    tabPaddingLeft = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsTabPaddingLeft,
            tabPaddingLeft);
    tabPaddingRight = a.getDimensionPixelOffset(R.styleable.PagerSlidingTabStripPlus_pstsTabPaddingRight,
            tabPaddingRight);
    tabPaddingTop = a.getDimensionPixelOffset(R.styleable.PagerSlidingTabStripPlus_pstsTabPaddingTop,
            tabPaddingTop);
    tabPaddingBottom = a.getDimensionPixelOffset(R.styleable.PagerSlidingTabStripPlus_pstsTabPaddingBottom,
            tabPaddingBottom);
    tabBackgroundResId = a.getResourceId(R.styleable.PagerSlidingTabStripPlus_pstsTabBackground,
            tabBackgroundResId);
    shouldExpand = a.getBoolean(R.styleable.PagerSlidingTabStripPlus_pstsShouldExpand, shouldExpand);
    scrollOffset = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsScrollOffset, scrollOffset);
    textAllCaps = a.getBoolean(R.styleable.PagerSlidingTabStripPlus_pstsTextAllCaps, textAllCaps);
    textColorTab = a.getColorStateList(R.styleable.PagerSlidingTabStripPlus_pstsTextColorTab);
    indicatorAlpha = a.getInteger(R.styleable.PagerSlidingTabStripPlus_pstsIndicatorAlpha, indicatorAlpha);
    hasDivider = a.getBoolean(R.styleable.PagerSlidingTabStripPlus_pstsHasDivider, hasDivider);
    tabTextSize = a.getDimensionPixelSize(R.styleable.PagerSlidingTabStripPlus_pstsTabTextSize, tabTextSize);
    tabsGravity = a.getInteger(R.styleable.PagerSlidingTabStripPlus_pstsTabsTitleGravity, tabsGravity);
    a.recycle();

    rectPaint = new Paint();
    rectPaint.setAntiAlias(true);
    rectPaint.setStyle(Style.FILL);

    dividerPaint = new Paint();
    dividerPaint.setAntiAlias(true);
    dividerPaint.setStrokeWidth(dividerWidth);

    defaultTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.MATCH_PARENT);
    expandedTabLayoutParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f);

    if (locale == null) {
        locale = getResources().getConfiguration().locale;
    }

}

From source file:com.tapfortap.phonegap.TapForTapPhoneGapPlugin.java

private LayoutParams getLayoutParamsForOptions(JSONObject options) {
    int widthPx = options.optInt("width", LayoutParams.MATCH_PARENT);
    int heightPx = options.optInt("height", 50);
    float widthDip;
    if (widthPx > 0) {
        widthDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthPx,
                cordova.getActivity().getResources().getDisplayMetrics());
    } else {//from   w  w w . j av  a 2  s. c o  m
        widthDip = widthPx;
    }
    float heightDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightPx,
            cordova.getActivity().getResources().getDisplayMetrics());
    return new LayoutParams((int) widthDip, (int) heightDip);
}

From source file:com.anyline.reactnative.Document4Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getResources().getIdentifier("activity_scan_scanview", "layout", getPackageName()));

    // takes care of fading the error message out after some time with no error reported from the SDK
    errorMessageCleanup = new Runnable() {
        @Override// ww w .j  av  a 2  s .c om
        public void run() {
            if (Document4Activity.this.isFinishing()) {
                return;
            }
            if (System.currentTimeMillis() > lastErrorRecieved + ERROR_MESSAGE_DELAY) {
                if (errorMessage == null || errorMessageAnimator == null) {
                    return;
                }
                if (errorMessage.getAlpha() == 0f) {
                    errorMessage.setText("");
                } else if (!errorMessageAnimator.isRunning()) {
                    errorMessageAnimator = ObjectAnimator.ofFloat(errorMessage, "alpha",
                            errorMessage.getAlpha(), 0f);
                    errorMessageAnimator.setDuration(ERROR_MESSAGE_DELAY);
                    errorMessageAnimator.setInterpolator(new AccelerateInterpolator());
                    errorMessageAnimator.start();
                }
            }
            handler.postDelayed(errorMessageCleanup, ERROR_MESSAGE_DELAY);

        }
    };

    // Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    imageViewResult = (ImageView) findViewById(
            getResources().getIdentifier("image_result", "id", getPackageName()));
    errorMessageLayout = (FrameLayout) findViewById(
            getResources().getIdentifier("error_message_layout", "id", getPackageName()));
    errorMessage = (TextView) findViewById(
            getResources().getIdentifier("error_message", "id", getPackageName()));

    documentScanView = (ScanView) findViewById(
            getResources().getIdentifier("document_scan_view", "id", getPackageName()));
    // add a camera open listener that will be called when the camera is opened or an error occurred
    // this is optional (if not set a RuntimeException will be thrown if an error occurs)
    documentScanView.setCameraOpenListener(this);
    // the view can be configured via a json file in the assets, and this config is set here

    try {
        final JSONObject json = new JSONObject(configJson);
        documentScanView.setScanConfig(json, licenseKey);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // initialize Anyline with the license key and a Listener that is called if a result is found
    documentScanView.getScanViewPlugin().addScanResultListener(new DocumentScanResultListener() {
        @Override
        public void onResult(ScanResult documentResult) {

            // handle the result document images here
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            AnylineImage transformedImage = (AnylineImage) documentResult.getResult();
            AnylineImage fullFrame = documentResult.getFullImage();

            // resize display view based on larger side of document, and display document
            int widthDP, heightDP;
            Bitmap bmpTransformedImage = transformedImage.getBitmap();

            if (bmpTransformedImage.getHeight() > bmpTransformedImage.getWidth()) {
                widthDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100,
                        getResources().getDisplayMetrics());
                heightDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160,
                        getResources().getDisplayMetrics());
                //Add a comment to this line

                imageViewResult.getLayoutParams().width = widthDP;
                imageViewResult.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
            } else {
                widthDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 160,
                        getResources().getDisplayMetrics());
                heightDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100,
                        getResources().getDisplayMetrics());

                imageViewResult.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
                imageViewResult.getLayoutParams().height = heightDP;
            }

            imageViewResult.setImageBitmap(
                    Bitmap.createScaledBitmap(transformedImage.getBitmap(), widthDP, heightDP, false));

            /**
             * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because
             * keeping them in memory (e.g. setting the full frame to an ImageView)
             * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError
             * (Throwable)}
             *
             * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
             * for example
             *
             */
            File outDir = new File(getCacheDir(), "ok");
            outDir.mkdir();
            // change the file ending to png if you want a png
            JSONObject jsonResult = new JSONObject();
            try {
                // convert the transformed image into a gray scaled image internally
                // transformedImage.getGrayCvMat(false);
                // get the transformed image as bitmap
                // Bitmap bmp = transformedImage.getBitmap();
                // save the image with quality 100 (only used for jpeg, ignored for png)
                File imageFile = TempFileUtil.createTempFileCheckCache(Document4Activity.this,
                        UUID.randomUUID().toString(), ".jpg");
                transformedImage.save(imageFile, quality);
                showToast(getString(
                        getResources().getIdentifier("document_image_saved_to", "string", getPackageName()))
                        + " " + imageFile.getAbsolutePath());

                jsonResult.put("imagePath", imageFile.getAbsolutePath());

                // Save the Full Frame Image
                if (fullFrame != null) {
                    imageFile = TempFileUtil.createTempFileCheckCache(Document4Activity.this,
                            UUID.randomUUID().toString(), ".jpg");
                    fullFrame.save(imageFile, quality);
                    jsonResult.put("fullImagePath", imageFile.getAbsolutePath());
                }
                // Put outline and conficence to result
                jsonResult.put("outline", jsonForOutline(documentResult.getOutline()));
                jsonResult.put("confidence", documentResult.getConfidence());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException jsonException) {
                //should not be possible
                Log.e(TAG, "Error while putting image path to json.", jsonException);
            }

            // release the images
            transformedImage.release();
            fullFrame.release();

            Boolean cancelOnResult = true;

            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(configJson);
                cancelOnResult = jsonObject.getBoolean("cancelOnResult");
            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }

            if (cancelOnResult) {
                ResultReporter.onResult(jsonResult, true);
                setResult(AnylineSDKPlugin.RESULT_OK);
                finish();
            } else {
                ResultReporter.onResult(jsonResult, false);
            }

        }

        @Override
        public void onPreviewProcessingSuccess(AnylineImage anylineImage) {
            // this is called after the preview of the document is completed, and a full picture will be
            // processed automatically
        }

        @Override
        public void onPreviewProcessingFailure(DocumentScanViewPlugin.DocumentError documentError) {
            // this is called on any error while processing the document image
            // Note: this is called every time an error occurs in a run, so that might be quite often
            // An error message should only be presented to the user after some time

            showErrorMessageFor(documentError);
        }

        @Override
        public void onPictureProcessingFailure(DocumentScanViewPlugin.DocumentError documentError) {

            showErrorMessageFor(documentError, true);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            // if there is a problem, here is how images could be saved in the error case
            // this will be a full, not cropped, not transformed image
            AnylineImage image = ((DocumentScanViewPlugin) documentScanView.getScanViewPlugin())
                    .getCurrentFullImage();

            if (image != null) {
                File outDir = new File(getCacheDir(), "error");
                outDir.mkdir();
                File outFile = new File(outDir,
                        "" + System.currentTimeMillis() + documentError.name() + ".jpg");
                try {
                    image.save(outFile, 100);
                    Log.d(TAG, "error image saved to " + outFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.release();
            }
        }

        @Override
        public boolean onDocumentOutlineDetected(List rect, boolean documentShapeAndBrightnessValid) {
            // is called when the outline of the document is detected. return true if the outline is consumed by
            // the implementation here, false if the outline should be drawn by the DocumentScanView
            lastOutline = rect; // saving the outline for the animations
            return true;
        }

        @Override
        public void onTakePictureSuccess() {
            // this is called after the image has been captured from the camera and is about to be processed
            progressDialog = ProgressDialog.show(Document4Activity.this,
                    getString(getResources().getIdentifier("document_processing_picture_header", "string",
                            getPackageName())),
                    getString(getResources().getIdentifier("document_processing_picture", "string",
                            getPackageName())),
                    true);

            if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) {

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        errorMessageAnimator.cancel();
                        errorMessageLayout.setVisibility(View.GONE);
                    }
                });

            }
        }

        @Override
        public void onTakePictureError(Throwable throwable) {
            // This is called if the image could not be captured from the camera (most probably because of an
            // OutOfMemoryError)
            throw new RuntimeException(throwable);
        }

        @Override
        public void onPictureCornersDetected(AnylineImage anylineImage, List rect) {
            // this is called after manual corner detection was requested
            // Note: not implemented in this example
        }

        @Override
        public void onPictureTransformed(AnylineImage anylineImage) {
            // this is called after a full frame image and 4 corners were passed to the SDK for
            // transformation (e.g. when a user manually selected the corners in an image)
            // Note: not implemented in this example
        }

        @Override
        public void onPictureTransformError(DocumentScanViewPlugin.DocumentError documentError) {
            // this is called on any error while transforming the document image from the 4 corners
            // Note: not implemented in this example
        }

    });

    // optionally stop the scan once a valid result was returned
    // documentScanView.setCancelOnResult(cancelOnResult);

}

From source file:com.nextgis.maplibui.formcontrol.Combobox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {

    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_NAME_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;//  w  w w.j  a v  a2  s . c  o  m
    if (ControlHelper.hasKey(savedState, mFieldName))
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
    else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        if (column >= 0)
            lastValue = featureCursor.getString(column);
    } else if (mIsShowLast)
        lastValue = preferences.getString(mFieldName, null);

    int defaultPosition = 0;
    int lastValuePosition = -1;
    mAliasValueMap = new HashMap<>();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.formtemplate_spinner);
    setAdapter(spinnerArrayAdapter);

    if (attributes.has(ConstantsUI.JSON_NGW_ID_KEY) && attributes.getLong(ConstantsUI.JSON_NGW_ID_KEY) != -1) {
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        if (null == map)
            throw new IllegalArgumentException("The map should extends MapContentProviderHelper or inherited");

        String account = element.optString(SyncStateContract.Columns.ACCOUNT_NAME);
        long id = attributes.getLong(JSON_NGW_ID_KEY);
        for (int i = 0; i < map.getLayerCount(); i++) {
            if (map.getLayer(i) instanceof NGWLookupTable) {
                NGWLookupTable table = (NGWLookupTable) map.getLayer(i);
                if (table.getRemoteId() != id || !table.getAccountName().equals(account))
                    continue;

                int j = 0;
                for (Map.Entry<String, String> entry : table.getData().entrySet()) {
                    mAliasValueMap.put(entry.getValue(), entry.getKey());

                    if (null != lastValue && lastValue.equals(entry.getKey()))
                        lastValuePosition = j;

                    spinnerArrayAdapter.add(entry.getValue());
                    j++;
                }

                break;
            }
        }
    } else {
        JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
        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 value_alias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

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

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

                mAliasValueMap.put(value_alias, value);
                spinnerArrayAdapter.add(value_alias);
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);

    // The drop down view
    spinnerArrayAdapter.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);
}

From source file:alexander.martinz.libs.materialpreferences.MaterialEditTextPreference.java

private float convertDpToPixels(int dp) {
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, metrics);
}

From source file:com.androguide.honamicontrol.MainActivity.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override//from  w ww .  j  a v a  2s. co m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_main);
    headers.add("Welcome");
    headers.add("Kernel Control");
    headers.add("Sound Control");
    headers.add("Touch Screen");
    headers.add("Help Center");

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

    ArrayAdapter<String> pimpAdapter = new ArrayAdapter<String>(this, R.layout.drawer_list_item,
            mDrawerHeaders);
    mDrawerList.setAdapter(pimpAdapter);

    View child = mDrawerList.getChildAt(mDrawerList.getFirstVisiblePosition());

    if (child != null && android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
        child.setBackground(getColouredTouchFeedback());
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    /**
     * ActionBarDrawerToggle ties together the proper interactions between
     * the sliding drawer and the action bar app icon
     */
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.open_drawer,
            R.string.close_drawer) {

        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    /** Tabs adapter using the PagerSlidingStrip library */
    tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
    pager = (ViewPager) findViewById(R.id.pager);
    MyPagerAdapter adapter = new MyPagerAdapter(this.getSupportFragmentManager());
    pager.setAdapter(adapter);
    pager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });

    final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
            getResources().getDisplayMetrics());
    pager.setPageMargin(pageMargin);

    tabs.setViewPager(pager);
    tabs.setOnPageChangeListener(this);

    changeColor(Color.parseColor(mAppColor));
    pager.setOffscreenPageLimit(5);
}

From source file:com.amitupadhyay.aboutexample.ui.widget.FabOverlapTextView.java

private void recompute(int width) {
    if (text != null) {
        // work out the top padding and line height to align text to a 4dp grid
        final float fourDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
                getResources().getDisplayMetrics());

        // ensure that the first line's baselines sits on 4dp grid by setting the top padding
        final Paint.FontMetricsInt fm = paint.getFontMetricsInt();
        final int gridAlignedTopPadding = (int) (fourDip
                * (float) Math.ceil((unalignedTopPadding + Math.abs(fm.ascent)) / fourDip)
                - Math.ceil(Math.abs(fm.ascent)));
        super.setPadding(getPaddingLeft(), gridAlignedTopPadding, getPaddingTop(), getPaddingBottom());

        // ensures line height is a multiple of 4dp
        final int fontHeight = Math.abs(fm.ascent - fm.descent) + fm.leading;
        final int baselineAlignedLineHeight = (int) (fourDip * (float) Math.ceil(lineHeightHint / fourDip));

        // before we can workout indents we need to know how many lines of text there are;
        // so we need to create a temporary layout :(
        layout = StaticLayout.Builder.obtain(text, 0, text.length(), paint, width)
                .setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f).setBreakStrategy(breakStrategy)
                .build();// w ww  .  j  av a  2  s .c om
        final int preIndentedLineCount = layout.getLineCount();

        // now we can calculate the indents required for the given fab gravity
        final boolean gravityTop = (fabGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.TOP;
        final boolean gravityLeft = (fabGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT;
        // we want to iterate forward/backward over the lines depending on whether the fab
        // overlap vertical gravity is top/bottom
        int currentLine = gravityTop ? 0 : preIndentedLineCount - 1;
        int remainingHeightOverlap = fabOverlapHeight - (gravityTop ? getPaddingTop() : getPaddingBottom());
        final int[] leftIndents = new int[preIndentedLineCount];
        final int[] rightIndents = new int[preIndentedLineCount];
        do {
            if (remainingHeightOverlap > 0) {
                // still have overlap height to consume, set the appropriate indent
                leftIndents[currentLine] = gravityLeft ? fabOverlapWidth : 0;
                rightIndents[currentLine] = gravityLeft ? 0 : fabOverlapWidth;
                remainingHeightOverlap -= baselineAlignedLineHeight;
            } else {
                // have consumed the overlap height: no indent
                leftIndents[currentLine] = 0;
                rightIndents[currentLine] = 0;
            }
            if (gravityTop) { // iterate forward over the lines
                currentLine++;
            } else { // iterate backward over the lines
                currentLine--;
            }
        } while (gravityTop ? currentLine < preIndentedLineCount : currentLine >= 0);

        // now that we know the indents, create the actual layout
        layout = StaticLayout.Builder.obtain(text, 0, text.length(), paint, width)
                .setLineSpacing(baselineAlignedLineHeight - fontHeight, 1f)
                .setIndents(leftIndents, rightIndents).setBreakStrategy(breakStrategy).build();

        // ensure that the view's height sits on the grid (as we've changed padding etc).
        final int height = getPaddingTop() + layout.getHeight() + getPaddingBottom();
        final float overhang = height % fourDip;
        if (overhang != 0) {
            super.setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
                    unalignedBottomPadding + (int) (fourDip - overhang));
        }
    }
}